5

I have an array that looks like this:

const arr = [
  [500, 'Foo'],
  [600, 'bar'],
  [700, 'Baz'],
];

I would like to sort this arr alphabetically by the second element in each inner array, ie:

[
  [600, 'bar'],
  [700, 'Baz'],
  [500, 'Foo'],
]

Note the case insensitivity. Also, I would love to use lodash helpers if they come in handy here!

4
  • 1
    Array.prototype.sort, no lodash or anything else is required. Commented Sep 19, 2016 at 23:02
  • 1
    _.orderBy(arr, x => x[1].toUpperCase()) Commented Sep 19, 2016 at 23:04
  • Read the docs, specifically the stuff about a custom compare function. Commented Sep 19, 2016 at 23:05
  • Well that was a fun discussion Commented Sep 19, 2016 at 23:21

2 Answers 2

10

Here is a concrete, working example, using Array.prototype.sort:

const arr = [
  [500, 'Foo'],
  [600, 'bar'],
  [700, 'Baz']
];

arr.sort((a,b) => a[1].toUpperCase().localeCompare(b[1].toUpperCase()));

console.log(arr);

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

Comments

2

Array.prototype.sort takes a function which will be applied to each pair of items in the array. The return of that function determines how the items are sorted (it needs to return a positive number, 0, or a negative number).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.