1

Question: How do I sort my data array by two properties:

  1. where type is always on top and
  2. where count is always from smallest to largest.

This is my effort:

var data = [
  {type: 'first', count: '1'},
  {type: 'second', count: '5'},
  {type: 'first', count: '2'},
  {type: 'second', count: '2'},
  {type: 'second', count: '1'},
  {type: 'first', count: '0'},
]

//Expected
var newData = [
  {type: 'first', count: '0'},
  {type: 'first', count: '1'},
  {type: 'first', count: '2'},
  {type: 'second', count: '1'},
  {type: 'second', count: '2'},
  {type: 'second', count: '5'},
]

 //**Pseudo code**//
// Will put the types on top
data.sort((a,b) => a.type === 'first' ? -1:0)

// This will sort the count 
data.sort((a,b) => a.count < b.count ? -1 ? (a.count > b.count ? 1:0)

Since count share the values between different types, I'm finding it difficult to solve it. How can I sort both these properties but keeping type always on top, and count always in order from small to large?

acornagl
  • 521
  • 5
  • 24
Armeen Moon
  • 18,061
  • 35
  • 120
  • 233
  • Why is there no `type: 'second', count: '1'` element in your `newData`? Do you expect your "sort" algorithm to omit it because the last `first` element has a `count` greater than its own? – Iain Galloway Feb 22 '17 at 17:28
  • how many types can be there? You may have to write a custom sort for this – Rahul Arora Feb 22 '17 at 17:31
  • 1
    Possible duplicate of [Javascript sort function. Sort by First then by Second](http://stackoverflow.com/questions/9175268/javascript-sort-function-sort-by-first-then-by-second) – Iain Galloway Feb 22 '17 at 17:31
  • @rahul it will always be "first" on top. "First"& "second" are a bit misleading names of values. – Armeen Moon Feb 22 '17 at 17:33

1 Answers1

1

You can use sort() method like this.

var data = [
  {type: 'first', count: '1'},
  {type: 'second', count: '5'},
  {type: 'first', count: '2'},
  {type: 'second', count: '2'},
  {type: 'second', count: '1'},
  {type: 'first', count: '0'},
]

var result = data.sort(function(a, b) {
  return ((b.type == 'first' ) - (a.type == 'first')) || (a.count - b.count)
})

console.log(result)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176