非常强力的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);
posted @ 2018-07-30 15:56  Jone_chen  阅读(272)  评论(0编辑  收藏  举报