let ary = [{ age: 9},{age: 1},{age: 8},{ age:2},{age: 7},{age: 3}]
let sortByMySelf = function (arr, key) {
return arr.reduce((total, next) => {
let findIndex = total.findIndex((item) => {
return item[key] > next[key]
})
return findIndex === -1 ? total.concat([next]) : total.splice(findIndex, 0, next) && total
}, [])
}
let result = sortByMySelf(ary, 'age')
console.log(result, 'result');
- reduce 初始化一个新数组
- 在新数组中年查找一个项的索引,该项的值要比下一项的值大,
- 如果找到符合条件的项目:就把该项目插入对应索引值的前边,
- 由于splice(index,0) 返回空数组(为true),且splice 会让原数组改变 所以需要 &&total 将改变后的total 返回 供下次循环使用