Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a map by a specific field in es6 / React?

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?

like image 285
Robbie Avatar asked Jul 07 '18 01:07

Robbie


2 Answers

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>
   ))
}
like image 135
Andria Avatar answered Oct 13 '22 00:10

Andria


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>
))}
like image 25
Tholle Avatar answered Oct 13 '22 01:10

Tholle