12

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?

5

2 Answers 2

17

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>
   ))
}
4
  • double check the return of sort
    – charlietfl
    Jul 7, 2018 at 1:35
  • Sorry, I forgot to finish typing it. But I put it in the top part, it sorts them from lowest to hightest, I tested that part.
    – Andria
    Jul 7, 2018 at 1:37
  • Worked like a charm!
    – Robbie
    Jul 7, 2018 at 1:39
  • @ChrisBrownie55 You have a typo in .sort(({ id: previousID }, { id: currentID }) => previoudID - currentID) (previoudID should be previousID).
    – kenold
    Nov 14, 2019 at 16:05
9

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>
))}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.