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.
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.
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.
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.
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.
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.
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