I've got this map that I'd like to sort by "id" value:
{products.map(({ id, headline }) => (
<Container>
<Row key={id}>
<Col>
<p>id={id}</p>
<p>headline={headline}</p>
</Col>
</Row>
</Container>
))}
How would I do this?
Assuming id
is a number you can do products.sort(({id: previousID}, {id: currentID}) => previousID - currentID)
Like so:
JavaScript Code:
{products
.sort(({ id: previousID }, { id: currentID }) => previousID - currentID)
.map(({ id, headline }) => (
<Container key={id}>
<Row>
<Col>
<p>id={id}</p>
<p>headline={headline}</p>
</Col>
</Row>
</Container>
))
}
You could sort
the array before you map
it:
{products.sort((a, b) => a.id - b.id).map(({ id, headline }) => (
<Container>
<Row key={id}>
<Col>
<p>id={id}</p>
<p>headline={headline}</p>
</Col>
</Row>
</Container>
))}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With