1

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
      }
    ]
  }
]
7
  • Can you post your desired output? Commented Jul 24, 2018 at 20:29
  • What is a[Object.keys(a)[0]] supposed to do? Commented Jul 24, 2018 at 20:31
  • @JonasW. I imagine it's supposed to grab the value corresponding to the first property of a, though that's a terrible idea. Commented Jul 24, 2018 at 20:32
  • @JonasW. yes, it's an id Commented Jul 24, 2018 at 20:33
  • Numbers generally don't have a "position" property on them... Commented Jul 24, 2018 at 20:33

1 Answer 1

3

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.