您好,欢迎来到暴趣科技网。
搜索
您的当前位置:首页reduce排序

reduce排序

来源:暴趣科技网
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 返回 供下次循环使用

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baoquwan.com 版权所有 湘ICP备2024080961号-7

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务