0

I need to sort an complex array order by one column of the array.

For example, this array might looks like

array = [["Banana","Chapter3"], ["Orange","Chapter2"], ["Apple","Chapter1"]];

I want it to sort by Chapter, so the result will be

array = ["Apple","Chapter1"],["Orange","Chapter2"],["Banana","Chapter3"]]

But if I do array.sort, it will become

[["Apple","Chapter1"],["Banana","Chapter3"],["Orange","Chapter2"]]

It seems sort by first element's ascii code. How do I sort by specific element in array?

I also created a JSfiddle to illustrate my idea.

1

1 Answer 1

0

You need to pass a comparator to sort:

var array = [["Banana","Chapter3"], ["Orange","Chapter2"], ["Apple","Chapter1"]];

var sorted = array.sort(function (a, b) {
  if (a[1] > b[1]) {
    return 1;
  } else if (a[1] < b[1]) {
    return -1;
  } else {
    return 0;
  }
});

console.log(sorted);

// [ [ 'Apple', 'Chapter1' ],
//   [ 'Orange', 'Chapter2' ],
//   [ 'Banana', 'Chapter3' ] ]
Sign up to request clarification or add additional context in comments.

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.