我有一个React对象数组,我想根据其中一个道具的值对它们进行排序。
var arr=[];
arr[0] = <Fruit name="orange" count={10}/>
arr[1] = <Fruit name"apple" count={5}/>
是否内置了React函数,我可以按照水果count
的升序对此数组进行排序?
答案 0 :(得分:6)
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} />
);
});
Here是说明排序函数输入和输出的小提琴
答案 1 :(得分:0)
如果要根据多个字段进行排序: - //使用lodash
sortingFunction(arrayTobeSorted) {
let sortedResults = sortBy(arrayTobeSorted, function(e) {
return [e.field1.trim().toUpperCase(), e.field2.trim().toUpperCase()];
});