jj008
jj008

Reputation: 1093

Sorting array of nested objects

I have the following data structure and I would like to sort them by "position".

[
  {
    "id": 52,
    "position": 2,
    "components_under_section": [
      {
       "id": 122,
       "position": 2
      },
      {
       "id": 123,
       "position": 1
      }
    ]
  },
  {
    "id": 53,
    "position": 1,
    "components_under_section": [
      {
       "id": 112,
       "position": 2
      },
      {
       "id": 113,
       "position": 1
      }
    ]
  }
]

Here's what I tried so far, I can sort the outer object but I can't sort the components_under_section. Did I miss anything? Thanks in advance.

array.sort( (a, b) => {
  let compAPosition = a[Object.keys(a)[0]]["position"];
  let compBPosition = b[Object.keys(b)[0]]["position"];

  if(a.components_under_section.length){
    a.components_under_section.sort ( (c, d) => {
      let compCPosition = c[Object.keys(c)[0]]["position"];
      let compDPosition = d[Object.keys(d)[0]]["position"];
      return ( compCPosition > compDPosition ? 1 : ((compDPosition > compCPosition ) ? -1 : 0 ) );
    })
  }

  return ( compAPosition > compBPosition ? 1 : ((compBPosition > compAPosition ) ? -1 : 0 ) );
})

Desired Output (sorting by components_under_section, then sort by outer object):

[
  {
    "id": 53,
    "position": 1,
    "components_under_section": [
      {
       "id": 113,
       "position": 1
      },
      {
       "id": 112,
       "position": 2
      }
    ]
  },
  {
    "id": 52,
    "position": 2,
    "components_under_section": [
      {
       "id": 123,
       "position": 1
      },
      {
       "id": 122,
       "position": 2
      }
    ]
  }
]

Upvotes: 1

Views: 69

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386883

You could take a callback for sorting by position and sort the outer array directly and then iterate and sort the inner arrays components_under_section.

const sortByPosition = (a, b) => a.position - b.position
array.sort(sortByPosition);
array.forEach(({ components_under_section }) => components_under_section.sort(sortByPosition));

Upvotes: 3

Related Questions