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

Sorting deeply nested objects in an Array using ES6

I’m fairly new to working with arrays and objects.
I have the array below that contains multiple objects and those objects contain 1 object called date and 1 nested array called data ( data contains 2 keys, date and expense )

I’m able to map over the array to output what I want.

Problem:
I cannot figure out how to sort the array alphabetically from A to Z without destructuring it.
I know I should use probably something like this function for the sorting but since it’s deeply nested, I cannot seem to properly hit a.expense.

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

.sort((a, b) => (a.expense > b.expense ? -1 : 1))

What I currently have going on:
Lets assume the array is called arr

      {arr.map((item) => {
              return item.data
                .map((d) => (
                  <div>
                    <div>{d.expense}</div> <div>{d.date}</div>
                  </div>
                )).sort((a, b) => (a.expense > b.expense ? -1 : 1)) // sorting doesnt work
      })}

enter image description here

>Solution :

The problem is you are mapping your data to JSX and then trying to sort it. You need to sort it before you map it to jsx:

      {arr.map((item) => {
              return item.data
                // sort first, then render
                .sort((a, b) => (a.expense > b.expense ? -1 : 1))
                .map((d) => (
                  <div>
                    <div>{d.expense}</div> <div>{d.date}</div>
                  </div>
                ))
      })}

But please know that this will sort your data on every render, which is a bit of a resource hog. It’s possible for your component to render multiple times without the data changing. You are better off sorting the data on the server (in your db call/query), or immediately after you load the data:

fetch(...)
  .then(res => res.json())
  .then(data => data.sort(...))
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