How would you sort a multidimensional array in JavaScript?
I have an array full of arrays that contain two dates and a string. I need the main array sorted by one of the date arrays, is this possible?
data stucture:
events = [
{ date 1, date 2, string },
{ date 2, date 2, string },
]
Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function.
Use sorted() with a lambda function to sort a multidimensional list by column. Call sorted(iterable, key=None) with key set to a lambda function of syntax lambda x: x[i] to sort a multidimensional list iterable by the i th element in each inner list x .
Approach: Create a temp[] array of size n^2. Starting with the first row one by one copy the elements of the given matrix into temp[]. Sort temp[]. Now one by one copy the elements of temp[] back to the given matrix.
Duplicate of sort outer array based on values in inner array, javascript here you will find several answers, like my own
var arr = [.....]
arr.sort((function(index){
return function(a, b){
return (a[index] === b[index] ? 0 : (a[index] < b[index] ? -1 : 1));
};
})(2)); // 2 is the index
This sorts on index 2
The array structure seems a little vague from your description. You can use a custom sort function to compare elements and do the sort.
Assuming the structure is:
var data = [
[date11, date12, string],
[date21, date22, string],
[date31, date32, string],
...
];
If you had objects instead of nested arrays, you wouldn't need to use number indexes. Here a[0]
and b[0]
are used to compare the first item in two nested arrays (assuming its the date you want to sort by). Also, assuming that a[0] and b[0] are already objects of Date - you may need to create the Date objects if they aren't already.
Update: Thanks to @maerics for pointing this out. The return value from the comparator needs to be [negative, 0, positive] corresponding to [a < b, a == b, a > b] values.
function sortByDate(a, b) {
return a[0].getTime() - b[0].getTime();
}
data.sort(sortByDate);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With