Hannie
Hannie

Reputation: 43

Sort array of objects by field and then alphabetically

I have an array of objects that looks like this:

  [
      {name: 'George', favNum: '1'},
      {name: 'Susan', favNum: '2'},
      {name: 'Bob', favNum: '1'},
      {name: 'Anna', favNum: '2'}
  ]

I want to sort the array first by the favNum field and then alphabetically within the resulting sort order. The end result would look like this:

  [
      {name: 'Bob', favNum: '1'},
      {name: 'George', favNum: '1'},
      {name: 'Anna', favNum: '2'},
      {name: 'Susan', favNum: '2'}
  ]

Is there a way to do with with Javascript? To give context, I've tried something like this after searching through other posts but am still having trouble getting the right sort order:

.sort((first, second) => {
      if (first.favNum === second.favNum) {
        return first.name > second.name ? 1 : -1
      }

      return first.favNum >= second.favNum
    })

Upvotes: 2

Views: 96

Answers (1)

Nenad Vracar
Nenad Vracar

Reputation: 122027

You can first sort my favNum and then use localeCompare to sort by name.

var data = [{name: 'George', favNum: '1'},{name: 'Susan', favNum: '2'},{name: 'Bob', favNum: '1'},{name: 'Anna', favNum: '2'}]
  
data.sort(function(a, b) {
  return a.favNum - b.favNum || a.name.localeCompare(b.name)
})

console.log(data)

Upvotes: 3

Related Questions