简体   繁体   English

排序数组但嵌套 arrays 的值

[英]Sort Array but values of nested arrays

I have an array I am passing into a chart.我有一个要传递给图表的数组。 However the order of the array matters so that the charts will plots the values left to right.但是数组的顺序很重要,因此图表将从左到右绘制值。

Here is the array in question:这是有问题的数组:

0: ["time", "amount"]
1: [2130, 1100]
2: [2129, 1000]
3: [2136, 2000]

The index of 0 for the nested array is time represented in 24 hour time as a number.嵌套数组的索引 0 是以 24 小时时间表示的时间为数字。 I need the array to be ordered chronologically based on the values in the sub-arrays index 0.我需要根据子数组索引 0 中的值按时间顺序对数组进行排序。

How can I go about doing this in javascript?我如何在 javascript 中执行此操作?

You can use the Array sort() method to order the array by the first element in each sub-array.您可以使用 Array sort()方法按每个子数组中的第一个元素对数组进行排序。

 const arr = [ [2130, 1100], [2129, 1000], [2136, 2000] ]; const sorted = arr.sort((a, b) => a[0] - b[0]); console.log(sorted);

You need to take account of the fact that your first array element contains text values, you can effectively chop that off and then sort what remains and add it back.您需要考虑到您的第一个数组元素包含文本值这一事实,您可以有效地将其切掉,然后对剩余的内容进行排序并将其添加回来。 You sort based on the 0 element of the subarrays:您根据子数组的0元素进行排序:

 let data = [ ["time", "amount"], [2130, 1100], [2129, 1000], [2136, 2000] ]; data = [data[0]].concat(data.slice(1).sort((a, b) => a[0] - b[0])); console.log(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM