Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – Order array of Json objects by key value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading