JavaScript Arrays Sorting multidimensional array

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Given the following array

var array = [
  ["key1", 10],
  ["key2", 3],
  ["key3", 40],
  ["key4", 20]
];

You can sort it sort it by number(second index)

array.sort(function(a, b) {
  return a[1] - b[1];
})
6
array.sort((a,b) => a[1] - b[1]);

This will output

[
  ["key2", 3],
  ["key1", 10],
  ["key4", 20],
  ["key3", 40]
]

Be aware that the sort method operates on the array in place. It changes the array. Most other array methods return a new array, leaving the original one intact. This is especially important to note if you use a functional programming style and expect functions to not have side-effects.



Got any JavaScript Question?