js reduce函数的使用方法 对象累加
dearweb
发布:2021-08-18 16:33:57阅读:
reduce() 方法 ,计算数组元素 相加后的总和 ,看网上给的Demo 全是 [1,2,3,4,6].reduce 这种基本用法,本次我将使用 reduce 实现 数组对象中 具体属性 Price 累加 [{ name: 'apple', price: 10 }, { name: 'banana', price: 9 } ];
基本用法

实例代码
数组求和的方法
let array = [
{
name: 'apple',
price: 10
},
{
name: 'banana',
price: 9
}
];
let sumprice = 0;
for (let index = 0; index < array.length; index++) {
const element = array[index];
sumprice += element.price;
}
console.log('for example sumprice',sumprice);
/*
reduce 语法实现
total 必需。初始值, 或者计算结束后的返回值。
currentValue 必需。当前元素
currentIndex 可选。当前元素的索引
arr 可选。当前元素所属的数组对象。
*/
sumprice = array.reduce(function (total, currentValue, currentIndex, arr) {
return total + currentValue.price;
}, 0);
console.log('for reduce sumprice',sumprice);数组求最大值
const a = [23,123,342,12];
const max = a.reduce(
function(pre,cur,inde,arr){
return pre>cur?pre:cur;
});
// 342多维的叠加执行操作
let result = [
{ subject: 'math', score: 88 },
{ subject: 'chinese', score: 95 },
{ subject: 'english', score: 80 }
];
let dis = {
math: 0.5,
chinese: 0.3,
english: 0.2};
let res = result.reduce((accumulator, cur) => dis[cur.subject] * cur.score + accumulator, 0);对象数组去重
const hash = {};
chatlists = chatlists.reduce((obj, next: Object) => {
const hashId = `${next.topic}_${next.stream_id}`; if (!hash[hashId]) {
hash[`${next.topic}_${next.stream_id}`] = true;
obj.push(next);
} return obj;
}, []);compose函数
redux compose源码实现
function compose(...funs) {
if (funs.length === 0) {
return arg => arg;
}
if (funs.length === 1) {
return funs[0];
}
return funs.reduce((a, b) => (...arg) => a(b(...arg)))
}数组累加
var arr = [
{ val: 1, name: '张三' },
{ val: 2, name: '张三' },
{ val: 3, name: '张三' },
{ val: 4, name: '张三' },
{ val: 5, name: '张三' },
]
var sum = arr.reduce(
function (prev, cur, index, arr) {
console.log(prev, cur, index)
return [...prev, cur]
},
[{ val: 0, name: '张三' }]
)
console.log(sum)
0: {val: 0, name: '张三'}
1: {val: 1, name: '张三'}
2: {val: 2, name: '张三'}
3: {val: 3, name: '张三'}
4: {val: 4, name: '张三'}
5: {val: 5, name: '张三'}拓展知识
reduceRight() 函数,该方法用法与reduce()其实是相同的,只是遍历的顺序相反,它是从数组的最后一项开始,向前遍历到第一项。
reduce() 是数组的归并方法,与forEach()、map()、filter()等迭代方法一样都会对数组每一项进行遍历,但是reduce() 可同时将前面数组项遍历产生的结果与当前遍历项进行运算,这一点是其他迭代方法无法企及的。
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧