Search code examples
javascriptreactjssortingreact-props

How to sort an array that is using map method by props in Javascript/React


I have an array called products that is using the map method to list all the elements inside it and i am trying to sort those elements by the price prop. I've tried all types of sort methods and functions but i can't get it to work.

JS

const recentprods = products.map(prod => {
  return <TableRow name={prod.name} price={prod.price} />
})

I tried:

const recentprods = products.map(prod => {
  return <TableRow name={prod.name} price={prod.price} />
}).sort((a,b) => a.price < b.price)

and

recentprods.sort() 

Essentially how could one sort a react component by its props?


Solution

  • You should apply the sorting before mapping.

    const recentprods = products
      .sort((a,b) => a.price - b.price)
          // if you want to change the sorting direction: b.price - a.price
      .map(prod => {
         return <TableRow name={prod.name} price={prod.price} />
      });