1

I've got a nested array that I want to sort by the values in the inner array. First sort by name alphabetically and next by date (from oldest to newest).

Let's say we have this array:

[['BBB','2020-10-20'],['AAA','2020-10-25'],['BBB','2020-10-19'],['EEE','2020-11-19'],['AAA','2020-10-10']]

After sorting it would look like this:

[['AAA','2020-10-10'],['AAA','2020-10-25'],['BBB','2020-10-19'],['BBB','2020-10-20'],['EEE','2020-11-19']]

Is it possible to do this with the sort() method?

1 Answer 1

3

Solution:

You can sort both based on the first and second column in one line of code.

You just need to do a sorting for strings and date objects:

var myArray  = 
[['BBB','2020-10-20'],
['AAA','2020-10-25'],
['BBB','2020-10-19'],
['EEE','2020-11-19'],
['AAA','2020-10-10']];

 myArray.sort( (a,b) => a[0].charCodeAt(0)-b[0].charCodeAt(0) || new Date(a[1]) - new Date(b[1]));

console.log(myArray);

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

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.