ReactJS: How to sort an array of objects based on attribute values?

I have an array of React objects, and I want to sort them based on the value of one of my details.

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

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

+4
source share
2 answers

React does not have a built-in function to handle this (what I know), but you can use something like lodash to achieve what you want. I would also suggest changing the structure of your data a bit. See an 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} />
   );
});

- ,

+6

: -// lodash

sortingFunction(arrayTobeSorted) {
let sortedResults = sortBy(arrayTobeSorted, function(e) {
return [e.field1.trim().toUpperCase(), e.field2.trim().toUpperCase()];
});
0

Source: https://habr.com/ru/post/1609594/


All Articles