javascript ReactJS:如何根据道具的值对对象数组进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32861889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:50:10  来源:igfitidea点击:

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

javascriptarrayssortingreactjs

提问by maxx777

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

我有一组 React 对象,我想根据其中一个道具的值对它们进行排序。

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?

是否有内置的 React 函数可以用来按水果的升序对这个数组进行排序count

回答by deowk

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

React 没有内置函数来处理这个(我知道),但是你可以使用lodash 之类的东西来实现你想要的。我还建议您稍微更改数据的结构。看看下面的例子。

// 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} />
   );
});

Hereis a fiddle to illustrate the sorting function input and output

这里有一个小提琴来说明排序函数的输入和输出

回答by Vichu

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

如果要根据多个字段进行排序:- //使用 lodash

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