reduce() 方法对数组中的每个元素执行一个由您提供的reduce函数(升序执行),将其结果汇总为单个返回值。reduce方法可做的事情特别多,就是循环遍历能做的,reduce都可以做,比如数组求和、数组求积、数组中元素出现的次数、数组去重等等。
arr.reduce(function(prev,cur,index,arr){
...
}, init);
参数:
- prev 必需。累计器累计回调的返回值; 表示上一次调用回调时的返回值,或者初始值 init;
- cur 必需。表示当前正在处理的数组元素;
- index 可选。表示当前正在处理的数组元素的索引,若提供 init 值,则起始索引为- 0,否则起始索引为1;
- arr 可选。表示原数组;
- init 可选。表示初始值。
这里以数组求和举例:
没有设置函数的初始迭代值
const arr = [1,2,3,4,5];
const sum = arr.reduce(function(prev,cur,index,arr){
console.log(prev,cur,index);
return prev + cur;
});
console.log('arr:',arr,'sum:',sum);
运行结果:
设置函数的初始迭代值
const arr = [1,2,3,4,5];
const sum = arr.reduce(function(prev,cur,index,arr){
console.log(prev,cur,index);
return prev + cur;
},5);
console.log('arr:',arr,'sum:',sum);
运行结果:
reduce的应用
1.计算数组中每个元素出现的次数
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice', 'Bob', 'Bob'];
var countedNames = names.reduce(function (allNames, name) {
console.log(allNames,name);
if (name in allNames) {
allNames[name]++;
}
else {
allNames[name] = 1;
}
return allNames;
}, {});
console.log(countedNames);
var arr = new Array(20);
for (var i = 0; i < arr.length; i++) {
arr[i] = Math.ceil(Math.random() * 10);
}
console.log(arr,"随机数组");
var countArrs = [];
let numArr = arr.reduce(function (prev, next) {
console.log(prev[next],"prev[next]");
prev[next] = prev[next] + 1 || 1;
countArrs.push({ prev });
console.log(prev[next],prev,"每一次的值")
return prev;
}, {});
console.log(numArr,"numArr是最终结果");
去除数组中重复的元素
let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'];
let myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
if (accumulator.indexOf(currentValue) === -1) {
accumulator.push(currentValue)
}
return accumulator;
}, []);
console.log(myOrderedArray); // - ['a','b','c','d']
let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
let result = arr.sort().reduce((init, current) => {
if(init.length === 0 || init[init.length-1] !== current) {
init.push(current);
}
return init;
}, []);
console.log(result); // - [1,2,3,4,5]
const data = [
{ id: 1, name: '张三', age: 15, },
{ id: 2, name: 'John', age: 18, },
{ id: 3, name: '李四', age: 18, },
{ id: 1, name: '张三', age: 15, },
{ id: 4, name: 'Jack', age: 18, },
{ id: 5, name: '王五', age: 10, },
{ id: 4, name: 'Jack', age: 18, },
{ id: 2, name: 'John', age: 18, },
];
let hash = {};
//如果hash:{curVal:{id:false}}就push data的这一项到新数组data2里,反之不push
const data2 = data.reduce((preVal, curVal) => {
hash[curVal.id] ? '' : hash[curVal.id] = true && preVal.push(curVal);
return preVal
}, [])
按属性对Object分类
var person = [
{
name: 'xiaoming',
age: 18
},{
name: 'xiaohong',
age: 17
},{
name: 'xiaogang',
age: 17
}
];
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
var key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
var groupedPerson = groupBy(person, 'age');
console.log(groupedPerson);
对对象的属性求和
let people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
];
let result = people.reduce((a,b) =>{
a = a + b.age;
return a;
},0)
console.log(result) // - 结果:61
找出重复项
function findDuplicates(arr) {
const distinct = new Set(arr); // 提高性能
const filtered = arr.filter((item) => {
// 在第一次遇到时从集合中删除元素
if (distinct.has(item)) {
distinct.delete(item);
}
// 在后续遇到时返回元素
else {
return item;
}
});
return [...new Set(filtered)];
}
const arr1 = [5, 5, 3, 4, 2, 3, 7, 5, 6];
const duplicates = findDuplicates(arr1);
console.log(duplicates);