Reputation: 99
I have an array complexArray
that I want to sort by the first value of its subarray (String). Sorting works as desired in the simpleArray
. For the complex array in use a custom sorting function which works fine with Int values (e.g. at position [1]) but not for the String at position [0].
How do I need to adapt the custom sorting function to make this work?
var simpleArray = ["2018-12-06T19:48:39Z","2018-12-15T19:48:39Z","2018-12-13T16:37:04Z"];
simpleArray.sort();
console.log(simpleArray);
var complexArray = [["2018-12-06T19:48:39Z", 1, "15m 10s"],["2018-12-15T19:48:39Z", 3, "16m 25s"],["2018-12-13T16:37:04Z", 2,"21m 41s"]];
complexArray.sort(function(a, b){
return a[0] - b[0];
});
console.log(complexArray);
Upvotes: 2
Views: 207
Reputation: 21489
You need to convert date strings to Date
object and then compare them in sort function.
var complexArray = [["2018-12-06T19:48:39Z", 1, "15m 10s"],["2018-12-15T19:48:39Z", 3, "16m 25s"],["2018-12-13T16:37:04Z", 2,"21m 41s"]]
complexArray.sort(function(a, b){
return new Date(a[0]) - new Date(b[0]);
});
console.log(complexArray);
Upvotes: 4