Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: sort multidimensional array

After creating a multi-dim array like this, how do I sort it?

Assuming 'markers' is already defined:

var location = []; for (var i = 0; i < markers.length; i++) {   location[i] = {};   location[i]["distance"] = "5";   location[i]["name"] = "foo";   location[i]["detail"] = "something"; } 

For the above example, I need to sort it by 'distance'. I've seen other questions on sorting arrays and multi-dim arrays, but none seem to work for this.

like image 314
Jeff Avatar asked Oct 07 '10 21:10

Jeff


People also ask

Can you sort a multidimensional array?

array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions. Associative (string) keys will be maintained, but numeric keys will be re-indexed.

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.

How do you sort a 2 D array?

To sort all elements of a 2D array by row-wise. As in the above rewrite program, the sort() method is used to iterate each element of a 2D array and sort the array row-wise. Finally, the print method displays all the elements of the 2D array.

How do you sort a two dimensional array by column value?

To sort 2 dimensional array by column value with JavaScript, we can use the array sort method. const arr = [ [12, "AAA"], [12, "BBB"], [12, "CCC"], [28, "DDD"], [18, "CCC"], [12, "DDD"], [18, "CCC"], [28, "DDD"], [28, "DDD"], [58, "BBB"], [68, "BBB"], [78, "BBB"], ]; const sortedArr = arr.


1 Answers

location.sort(function(a,b) {    // assuming distance is always a valid integer   return parseInt(a.distance,10) - parseInt(b.distance,10);  }); 

javascript's array.sort method has an optional parameter, which is a function reference for a custom compare. the return values are >0 meaning b first, 0 meaning a and b are equal, and <0 meaning a first.

like image 159
lincolnk Avatar answered Sep 21 '22 13:09

lincolnk