Javascript - Order array of Json objects by key value

Viewed 35

I have the following array of JSON objects:

[
  {
    term: 'summer'
  },
  {
    term: 'winter'
  },
  {
    term: 'fall'
  },
  {
    term: 'summer'
  },
  {
    term: 'summer'
  }
]

I was wondering how can order this array to be arranged by specific order of the term keys. For example the requested order is object with winter will be first then fall and then summer. So the expected result should be:

[
  {
    term: 'winter'
  },
  {
    term: 'fall'
  },
  {
    term: 'summer'
  },
  {
    term: 'summer'
  },
  {
    term: 'summer'
  }
]

Please advise how can I order the array to result in the expected array.

1 Answers

You can use Array#sort with a custom comparer function like so:

const data = [
  {
    term: 'summer'
  },
  {
    term: 'winter'
  },
  {
    term: 'fall'
  },
  {
    term: 'summer'
  },
  {
    term: 'summer'
  }
]

const SEASON_ORDER = ['winter', 'fall', 'summer', 'spring']

const seasonComparer = ({term: a}, {term: b}) => 
    SEASON_ORDER.indexOf(a) - SEASON_ORDER.indexOf(b)

console.log(data.sort(seasonComparer))

For custom comparer functions with parameters a and b, if the return value is:

  • greater than 0, then a is sorted to be after b
  • less than 0, then a is sorted to be before b
  • equal to 0, then the existing order is maintained

Note that if the ordering list is large, then you might like to use a map instead (constant time), to avoid the O(N) look-up time associated with Array#indexOf.

Related