kay
kay

Reputation: 1429

Sorting an array by and keep the order

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?

Upvotes: 0

Views: 76

Answers (1)

trincot
trincot

Reputation: 351183

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)

Upvotes: 5

Related Questions