0

I have data like this:

var data = [
  ['a', 2010], ['a', 2011], ['a', 2012],
  ['b', 2010], ['b', 2012], ['b', 2013],
  ['c', 2010], ['c', 2011], ['c', 2012],['c', 2013]
]

and I want sort this array by year but keep the order of data, so the output would be:

var data = [
  ['a', 2010], ['b', 2010], ['c', 2010], 
  ['a', 2011], ['c', 2011], 
  ['a', 2012], ['b', 2012], ['c', 2012],
  ['b', 2013], ['c', 2013]
]

As you can see, every data (a, b, c) does not always have data of each year (like b for 2011 or a for 2013)

If I use sort() function, it does sort by year but not in order.

var data = [
  ['a', 2010], ['a', 2011], ['a', 2012],
  ['b', 2010], ['b', 2012], ['b', 2013],
  ['c', 2010], ['c', 2011], ['c', 2012],['c', 2013]
]
var newData = data.sort(function(a, b) {
  return a[1] - b[1]
})
    
  console.log(newData)

How can I achieve this?

1
  • 1
    You seem to want to sort on two parameters rather than "keeping the order". Commented Apr 15, 2017 at 6:53

1 Answer 1

5

Add an expression to deal with ties: if a[1] - b[1] is zero, you should specify that then the order is determined by the first element:

var data = [
  ['a', 2010], ['b', 2011], ['c', 2012],
  ['b', 2010], ['b', 2012], ['b', 2013],
  ['c', 2010], ['c', 2011], ['c', 2012],['c', 2013]
]
var newData = data.sort(function(a, b) {
  return a[1] - b[1] || a[0].localeCompare(b[0]);
});
      
console.log(newData)

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.