Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a multidimensional array in javascript

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 },
 ]
like image 350
Kyle Hotchkiss Avatar asked May 13 '10 02:05

Kyle Hotchkiss


People also ask

Can you sort a multidimensional array?

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.

How do you sort a multidimensional list?

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 .

How do you sort a matrix in JavaScript?

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.


2 Answers

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

like image 188
Sean Kinsey Avatar answered Oct 22 '22 09:10

Sean Kinsey


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);
like image 33
Anurag Avatar answered Oct 22 '22 08:10

Anurag