Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: How do I sort an array of objects based on value of props?

I have an array of React objects and I want to sort them based on value of one of their props.

var arr=[];
arr[0] = <Fruit name="orange" count={10}/>
arr[1] = <Fruit name"apple" count={5}/>

Is there built in React function that I can use to sort this array in ascending order of fruit count?

like image 599
maxx777 Avatar asked Sep 30 '15 08:09

maxx777


People also ask

How do you sort an array of objects by a property value in React?

To sort an array of objects in React:Create a shallow copy of the array. Call the sort() method on the array passing it a function. The function is used to define the sort order.

How do you filter an array of objects in React?

To filter an array of objects in React:Call the filter() method on the array. On each iteration, check if a certain condition is met. The Array. filter methods returns an array with all elements that satisfy the condition.


1 Answers

React does not have a built in function to handle this (that I know of), but you could use something like lodash to achieve what you want. I would also suggest that you change the structure of your data slightly. Have a look at the example below.

// your data comes in like this  
var arr = [
    {name: "orange", count: 10}, 
    {name: "apple", count: 5},
    {name: "lemon", count: 11},
    {name: "grape", count: 2}
];

// order by ascending
var newArr = _.sortBy(arr, 'count', function(n) {
  return Math.sin(n);
});

// create your components
var fruits = newArr.map(function(fruit) {
   return(
      <Fruit name={fruit.name} count={fruit.count} />
   );
});

Here is a fiddle to illustrate the sorting function input and output

like image 53
deowk Avatar answered Nov 03 '22 08:11

deowk