user3967379
user3967379

Reputation:

Sort 2 dimensional array from largest to smallest string size based on first string in secondary array?

So say I have an array that looked something like this:

var array = [["This should be last", 1],
             ["This should be first I think", 1],
             ["This is the middle one", 1]];

The second value of each secondary array, which in this case is always 1, is arbitrary to the sorting. Now obviously .sort() will be of no direct use here. (Or maybe it will?)

I need to sort the array from largest to smallest string size. So after the sorting process it should look like this:

var array = [["This should be first I think", 1],
             ["This is the middle one", 1]
             ["This should be last", 1]];

How would I go about doing this?

Upvotes: 0

Views: 63

Answers (2)

Ori Drori
Ori Drori

Reputation: 192016

As sort uses a sort function you can just look into the the first element of the array, and sort by it:

array.sort(function(a, b) {
var aStr = a[0];
var bStr = b[0];
return bStr.length - aStr.length;
});

Upvotes: 0

Oriol
Oriol

Reputation: 288290

When you use sort you can provide your custom comparative function:

array.sort(function(a,b) {
  return b[0].length - a[0].length;
});

In ECMAScript 6, it can be simplified to

array.sort((a,b) => b[0].length - a[0].length);

Upvotes: 1

Related Questions