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
})}
CodePudding user response:
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(...))