3

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?

4 Answers 4

5

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} />
  });
Sign up to request clarification or add additional context in comments.

5 Comments

If i apply sorting before or after map, i can't access prod.price, prod.name, etc. How would i do that then?
Should i do another map over the sort method ?
@Uriel Why you cant access price and name? They are available inside the map function scope. Just copy and paste my code.
@Uriel Just updated my answer, probably the gt > sign was the issue. The minus operation should sort it out.
The sort method must return a number not a boolean as shown in my answer. :D
2

You want to normalize, sort, and otherwise alter your data as you see fit before applying it to React components. In the following case, the products array holds individual objects each with a price property, so sort the products array beforehand then map over the items.

The .sort method sorts the elements of an array in place and returns the sorted array. The chained .map method will iterate over the sorted array in the order prescribed.

I believe the following is a valid solution. Note that price is seen as a number. If it isn't, the sort may not work correctly.

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

Comments

2

So, yeah basically you need to sort it first and then map it, I've build an example for you:

constructor(props) {
    super(props);

    this.state = {
      products: [
        { name: 'Product 2', price: 2 },
        { name: 'Product 6', price: 6 },
        { name: 'Product 1', price: 1 },
        { name: 'Product 3', price: 3 },
        { name: 'Product 7', price: 7 },
        { name: 'Product 4', price: 4 },
        { name: 'Product 8', price: 8 },
        { name: 'Product 5', price: 5 },
      ],
    };
  }

  render() {
    return (
      <div>
        <h1>ONLY MAPPED</h1>
        {this.state.products.map((prod, i) => {
          return (
            <li key={i}>
              {prod.name} and its price: {prod.price}
            </li>
          );
        })}

        <h1>BOTH SORTED AND MAPPED.</h1>
        {this.state.products
          .sort((first, second) => {
            return first.price > second.price ? 1 : -1;
          })
          .map((prod, i) => {
            return (
              <li key={i}>
                {prod.name} and its price: {prod.price}
              </li>
            );
          })}
      </div>
    );
  }

Here you can check out the output

Comments

0

consider we have an array of objects with name and price properties.

const Products = [

{name:"p1",price: 5},
{name:"p2",price: 3},
{name:"p3",price: 2},
{name:"p4",price: 7},

]

We need to sort the Products array in ascending order by using its price property.

console.log(Products.sort((a,b) =>  a.price-b.price )); // descending b.price-a.price

output - >

[
  {name: "p3", price: 2},
  {name: "p2", price: 3},
  {name: "p1",  price: 5},
  {name: "p4", price: 7}
]

Now you can call map function with jsx element you want to add

Products.sort((a,b) =>  a.price-b.price ).map(data => {
   return <TableRow name={prod.name} price={prod.price} />;
});

PS: YOU can use this function directly in your code or use a helper function this way you make sure its sorted jsx.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.