1

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.

.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

4
  • What is the expected sorting order? Commented Oct 5, 2022 at 16:12
  • sorry my bad, just updated the question. Alphabetically from A to Z Commented Oct 5, 2022 at 16:19
  • You need to sort the data before you map it to JSX: return item.data.sort(...).map((d) => ...); Commented Oct 5, 2022 at 16:23
  • you mean sort the array before I map over it the first time or the second time ? Commented Oct 5, 2022 at 16:25

1 Answer 1

1

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(...))
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.