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?

2
  • 1
    I don't understand the sorting logic. Commented Apr 8, 2016 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. Commented Apr 8, 2016 at 22:42

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

1 Comment

And now turn it around to get the descending sort order.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.