JavaScript 如何按两个字段对对象数组进行排序
给定一个对象数组,任务是按对象的两个字段对数组进行排序。有两种方法可以解决这个问题,如下所述:
方法1
- 首先比较第一个属性,如果它们不相等,则按照相应的规则进行排序。
- 如果它们相等,则对第二个属性执行相同的操作。
示例: 该示例使用自定义比较函数实现上述方法。
// Create an array of objects
let arr = [
{ first: 3, second: 4 },
{ first: 3, second: 1 },
{ first: 1, second: 10 }
];
// Apply array.sort with comparison function
arr.sort(function (a, b) {
let af = a.first;
let bf = b.first;
let as = a.second;
let bs = b.second;
// If first value is same
if (af == bf) {
return (as < bs) ? -1 : (as > bs) ? 1 : 0;
} else {
return (af < bf) ? -1 : 1;
}
});
// Display output
console.log("'" + JSON.stringify(arr[0])
+ ", " + JSON.stringify(arr[1]) + ", "
+ JSON.stringify(arr[2]) + "'");
输出
'{"first":1,"second":10}, {"first":3,"second":1}, {"first":3,"second":4}'
方法2
- 首先比较第一个属性,如果它们不相等,则按照相应的顺序进行排序。
- 如果它们相等,则对第二个属性执行相同的操作,此示例遵循相同的方法,但使用 OR门 来减少代码量。
示例: 这个示例使用自定义比较函数来实现上述方法。
// Create input array of objects
let arr = [
{ first: 3, second: 4 },
{ first: 3, second: 1 },
{ first: 1, second: 10 }
];
// Apply array.sort with custom comparision funtion
arr.sort(function (a, b) {
// Compare first value then second
return a.first - b.first || a.second - b.second;
});
// Display the output
console.log("'" + JSON.stringify(arr[0])
+ ", " + JSON.stringify(arr[1]) + ", "
+ JSON.stringify(arr[2]) + "'");
输出
'{"first":1,"second":10}, {"first":3,"second":1}, {"first":3,"second":4}'