zoukankan      html  css  js  c++  java
  • 非常强力的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);
    
  • 相关阅读:
    洛谷 P1628 合并序列
    洛谷 P3378 【模板】堆
    浅谈可删除堆
    浅谈数据结构—分块
    浅谈对顶堆
    JDOJ 1929: 求最长不下降序列长度
    JDOJ 1928: 排队买票
    Leetcode(53)-最大子序和
    Leetcode(38)-报数
    Leetcode(35)-搜索插入位置
  • 原文地址:https://www.cnblogs.com/jone-chen/p/9391032.html
Copyright © 2011-2022 走看看