[英]sort array of objects by object field
I build an array like this 我建立一个像这样的数组
result.push({ id: id, reference: sometext });
Now I want to sort this array by reference
, which has some text. 现在,我想按
reference
对该数组进行排序,其中包含一些文本。
I tried this: 我尝试了这个:
result.sort(function(a,b) {
return result[a]-result[b];
});
This 这个
[ { id: 1, reference: 'banana' },
{ id: 2, reference: 'apple' } ]
should get 应得
[ { id: 2, reference: 'apple' },
{ id: 1, reference: 'banana' } ]
Do it like this instead: 改为这样做:
result.sort(function(a,b) {
return a.reference < b.reference ? -1 : 1;
});
Try this. 尝试这个。
result.sort(function(a,b) {
// Compare reference
if(a.reference < b.reference) {
// a's reference is lesser than the one in b
return -1;
} else if (a.reference == b.reference) {
// Both reference params are equal
return 0;
} else {
// a's reference is greater than that of b
return 1
}
});
This will return a sorted version of the results array. 这将返回结果数组的排序版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.