• 非常强力的reduce


    Array 的方法 reduce 是一个有非常多用处的函数。 它一个非常具有代表性的作用是将一个数组转换成一个值。但是你可以用它来做更多的事。

    1、使用"reduce"代替"map"

    function map(arr, exec) {
        return arr.reduce(function(res, item, index) {
            var newArr = exec(item, index);
            res.push(newArr);
            return res;
        }, [])
    }
    var _arr = map([10, 20, 30, 50], function(item) {
        return item * 2
    })
    console.log(_arr); // => [20, 40, 60, 100]
    

    2、使用"reduce"代替"filter"

    function filter(arr, exec) {
        return arr.reduce(function(res, item, index) {
            if (exec(item, index)) {
                res.push(item)
            }
            return res;
        }, [])
    
    }
    var _arr = filter([10, 20, 30, 50], function(item) {
        return item < 50
    })
    console.log(_arr); // => [10,20,30]
    

    3、应用

    计算数组中元素出现的次数(将数组转为对象)

    var cars = ['BMW', 'Benz', 'Benz', 'Tesla', 'BMW', 'Toyota'];
    var carsObj = cars.reduce(function(obj, name) {
        obj[name] = obj[name] ? ++obj[name] : 1;
        return obj;
    }, {});
    console.log(carsObj); // => { BMW: 2, Benz: 2, Tesla: 1, Toyota: 1 }
    

    去除数组对象中重复的值(根据对象的某一个key值,key重复就认为数组重复)

    var data = [{
        id: 0,
        name: 'jack',
        age: 30
    }, {
        id: 1,
        name: 'jackchen',
        age: 20
    }, {
        id: 2,
        name: 'eric',
        age: 15
    }, {
        id: 3,
        name: 'tomas',
        age: 20
    }, {
        id: 4,
        name: 'john',
        age: 20
    }, {
        id: 5,
        name: 'jacky',
        age: 20
    }]
    
    function unique(arr, key) {
        var hash = {};
        return arr.reduce((item, next) => {
            hash[next[key]] ? '' : (hash[next[key]] = true && item.push(next));
            return item;
        }, [])
    }
    var newData = unique(data, "age");
    console.log(newData);
    
  • 相关阅读:
    系统学Python-01
    pandas(二)
    matplotlib
    Python数据分析-初识numpy、pandas、scipy、matplotlib和Scikit-Learn等数据处理库
    Python进行读取或写入等文件操作时的路径问题
    pandas(一)
    00 Python及第三方库的安装问题
    sorted ()函数和列表中的sort()函数
    git 获取branch名和commit id
    查看Android log 和TEE Log
  • 原文地址:https://www.cnblogs.com/jone-chen/p/9391032.html
Copyright © 2020-2023  润新知