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
?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With