0

I have an nested array unsorted after sorting it should be sorted depending on 2nd item of sub-array

var unsorted = [["tag_17",0,4],["tag_18",13,18],["tag_435",6,11]];
var sorted = [["tag_18",13,18], ["tag_435",6,11], ["tag_17",0,4]];
2
  • 2
    btw, you have a nested array. Commented Jul 27, 2017 at 6:23
  • Sorry, Wrong choice of words :( Commented Jul 27, 2017 at 6:30

2 Answers 2

3

var a = [
  ["tag_17", 0, 4],
  ["tag_18", 13, 18],
  ["tag_435", 6, 11]
];

a.sort(sortFunction);
console.log(a);

function sortFunction(a, b) {
  if (a[0] === b[0]) {
    return 0;
  }
  return (a[1] < b[1]) ? 1 : -1;
}

You can read the documentation about sort.

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

4 Comments

Thanks buddy. It worked...
You're welcome. Up-vote and mark it as close. Happy Coding!!! :)
Found a working answer here too stackoverflow.com/a/12788202/2597670
Yes, just Google or StackOverflow and could have found multiple answers as sort is straight-forward and easy to use.
3

var unsorted = [["tag_17",0,4],["tag_18",13,18],["tag_435",6,11]];

sorted = unsorted.sort((a,b) => {
    return b[1] - a[1];
} )

console.log(sorted);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.