1

I have a single array looking like this:

var x = [[29,"Abc","9320","390"],[932,"123","9301","9032"], ...]

I'm looking to sort this array, so that it is organised by the first value of each array. In this case, that would look like this:

[[932,"123","9301","9032"], [29,"Abc","9320","390"], ...]

I've attempted to use .forEach but have been unable to get it working. Could anyone offer any suggestions?

GregW
  • 173
  • 6
  • 1
    I don't understand the sorting logic. – John Apr 08 '16 at 22:41
  • Hi @John - I'm looking to print out all of these arrays by order of their first value, so those with the largest value will be printed first. – GregW Apr 08 '16 at 22:42

2 Answers2

1

Try this:

var x = [[29,"Abc","9320","390"], [932,"123","9301","9032"]];

var sorted = x.sort(function(a, b) {
  return b[0] - a[0];
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

scott113341
  • 109
  • 4
  • The callback provided to the sort method should return a numerical value, negative, zero or positive. So `return b[0] - a[0]` would be more appropriate. – trincot Apr 08 '16 at 22:50
0

The proper way to do with sort is this:

var sorted = x.sort(function(a, b) {
  return a[0] - b[0];
}).reverse(); // the sort is in ascending order so we need to finally reverse the array to have your final array in descending order!

or even better:

var sorted = x.sort(function(a, b) {
  return b[0] - a[0];
})

if you compare the values using a < or > it wont always work:

Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?

However for numbers using a '-' is fine:

How to sort an array of integers correctly

Community
  • 1
  • 1
omarjmh
  • 13,632
  • 6
  • 34
  • 42