Array 的方法 reduce 是一个有很是多用处的函数。 它一个很是具备表明性的做用是将一个数组转换成一个值。可是你能够用它来作更多的事。数组
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]
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]
计算数组中元素出现的次数(将数组转为对象)函数
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重复就认为数组重复)code
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);