This is an incredibly basic question that I could do in Python in a matter of seconds- but I'm new to Javascript and maybe I just don't know the nomenclature for the language, but my research hasn't quite answered it.
I'm making an API call; and in response I've got:
let unordered_ranges = [[
[1461913200000, 57, 69],
[1380006000000, 75, 79],
[1321344000000, 78, 79],
[1276585200000, 69, 75],
[1252998000000, 68, 76],
[1234512000000, 79, 81],
[1423814400000, 77, 78],
[1489820400000, 69, 79]
]];
The first element in the nested arrays are timestamps in milliseconds. How do I sort the parent array chronologically using the nested timestamps?
So far I've got:
let ranges= unordered_ranges.sort(function (a, b) {
return a > b
});
I understand .sort() is lexicographic; so I need to pass my own function to sort it; however this function doesn't quite do it.
You'll want to access the first array entry (since you only have one) and then Array.prototype.sort()
with a standard numeric comparator using the first array item of each entry.
let unordered_ranges = [[ [1461913200000, 57, 69], [1380006000000, 75, 79], [1321344000000, 78, 79], [1276585200000, 69, 75], [1252998000000, 68, 76], [1234512000000, 79, 81], [1423814400000, 77, 78], [1489820400000, 69, 79] ]]; let ranges = unordered_ranges[0].sort((a, b) => a[0] - b[0]) console.info(ranges)
To explain the comparator, it's best to read the documentation...
If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If
a
andb
are two elements being compared, then:
- If
compareFunction(a, b)
is less than 0, sorta
to an index lower thanb
, iea
comes first.- If
compareFunction(a, b)
returns 0, leavea
andb
unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (eg Mozilla versions dating back to at least 2003) respect this.- If
compareFunction(a, b)
is greater than 0, sortb
to an index lower thana
, ieb
comes first.compareFunction(a, b)
must always return the same value when given a specific pair of elementsa
andb
as its two arguments. If inconsistent results are returned then the sort order is undefined.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.