0

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.

10
  • 1
    JSON is a textual notation for data exchange. (More here.) If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON. That's just an array of objects, no JSON in sight. Commented Sep 15, 2022 at 12:31
  • Please search thoroughly before posting. More about searching here. Commented Sep 15, 2022 at 12:32
  • Array.sort is typically employed like in a.sort((o1, o2)=>seasons.indexOf(o1.term) - seasons.indexOf(o2.term)) where seasons should be your season names in the funny order you want, i.e., ["winter", "fall", "summer"] :-? Commented Sep 15, 2022 at 12:34
  • @T.J.Crowder the sorting I need it not alphabetical or ascending/descending , its in a specific order. Unfortunately the examples in your link do not answer the need. Commented Sep 15, 2022 at 12:39
  • @kikon the sorting I need it not alphabetical or ascending/descending , its in a specific order. Unfortunately the examples in your link do not answer the need. Commented Sep 15, 2022 at 12:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Duplicate of stackoverflow.com/questions/18859186/… and probably several others.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.