// 数组对象排序方法
compare(property) {
return function (a, b) {
const value1 = a[property]
const value2 = b[property]
return value2 - value1 // 正序 return value1 - value2 降序
}
},
let arr = [ {name: '小明', age: 18},
{name: '小花', age: 20}]
比较两个人的年龄大小:
let newArr = arr.sort(this.compare('age'))
console.log(newArr)
计算两个人的年龄之和:
let sumCount = arr.reduce((ageSum, currStudent) => {
return ageSum + Number(currStudent.age);
}, 0)
console.log(sumCount)