梳理了一些 javascript 的入门开发经验,分享出来,欢迎指正学习。
是什么
reduce 是 javascript 数组中一个功能强大的函数,通常我们用它做以下操作
- 数组求和
- 数组去重
- 计算每个元素出现的次数
- 过滤数据
1. 数组求和
首先,我们要知道 reduce 函数接收4个参数:
- accumulator (acc) (累计器)、
- current value (cur) (当前元素的值)、
- current index (idx) (当前索引)、
- source array (src) (源数组,也就是正在遍历的对象)。
当回调函数第一次执行时,accumulator 和 current-value的取值有两种情况:
如果调用reduce()时提供了initialValue,accumulator取值为initialValue,current-value取数组中的第一个值;
如果没有提供 initialValue,那么accumulator取数组中的第一个值,currentValue取数组中的第二个值。
下面我们来写下求和函数
// 处理总和的累计器
const data = [1, 2, 3];
const total = data.reduce((acc, item) => {
return acc + item;
});
console.log("The sum is: ", total); //The sum is: 6
console.log("data: ", data); //data: [1, 2, 3]
可以看出,通过 reduce 的操作并没有改变原 data 的值。
2. 数组去重
const data = ['a', 'b', 'a', 'b', 'c', 'd', 'e'].reduce((acc,cur)=> {
if(acc.indexOf(cur)===-1) {
acc.push(cur);
}
return acc;
},[])
console.log("The repStringArray is: ", data); // data is: ["a", "b", "c", "d", "e"]
3.计算每个元素出现的次数
const initialValue = {};
const reducer = (tally, vote) => {
if (!tally[vote]) {
tally[vote] = 1;
} else {
tally[vote] = tally[vote] + 1;
}
return tally;
};
const words = [
"hello",
"world",
"hello",
"world",
"wxh",
];
const data = words.reduce((acc,cur)=>{
if(!acc[cur]) {
acc[cur] = 1;
} else {
acc[cur] = acc[cur] + 1;
}
return acc;
}, {});
console.log("data: ", data) // Result: {hello: 2, world: 2, wxh: 1}
4. 过滤数据
比如这样一个需求,在城市数组里筛选属于广东省的,然后给每个对象加上一个地区属性。 以往的做法是先用filter筛选出结果数组,再用map构造新的对象数组。这样其实遍历了两次数组,性能不够好。使用Array.reduce可以实现一次遍历就完成了:
const cities= [
{ city: '广州市', province: '广东省' },
{ city: '深圳市', province: '广东省' },
{ city: '石家庄市', province: '河北省' },
];
const data = cities
.reduce((acc, cur) => {
return cur.province=== '广东省'
? acc.concat(Object.assign({}, cur, { region: '华南区' }))
: acc;
}, [])
最后
以上是工作中可能会用到的 reduce 操作,当然 reduce 不单单只有这些使用场景,期待大家的分享。