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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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 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...;)
I've sorted the json before creating the React elements this Question helped me sorting the JSON arrays. Thanks @deowk
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()];
});

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.