5

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?

maxx777
  • 1,320
  • 1
  • 20
  • 37

2 Answers2

7

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

deowk
  • 4,280
  • 1
  • 25
  • 34
  • Thank you @deowk. Fiddle is working great with string values as well. We are already creating array from json. Just curious to know why you have created a map for it. And there is a problem that we are not using lodash in our project. Can you suggest some other solution? – maxx777 Sep 30 '15 at 09:27
  • @maxx777 Sure you don't have to use lodash the same thing could be achieved with a pure js function using the sort() function, as for the use of map - I frequently use it because it evaluates by insertion order thereby ensuring that the order stays the same...;) – deowk Sep 30 '15 at 09:36
  • I've sorted the json before creating the React elements [this Question](http://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript?rq=1) helped me sorting the JSON arrays. Thanks @deowk – maxx777 Sep 30 '15 at 09:53
0

If you want to sort depending on multiple fields:- //using lodash

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