发布于 2026-01-05 14 阅读
0

通过 10 个示例掌握 JavaScript 数组 reduce 方法

通过 10 个示例掌握 JavaScript 数组 reduce 方法

JavaScript 的 reduce 方法是一个强大的工具,它允许开发者遍历数组并累加单个值或对象。在本教程中,我们将学习如何使用 reduce 方法解决实际问题,从简单的求和与乘法到更高级的任务,例如从数组中删除重复项和验证括号。

图像

在本教程结束时,您将对如何使用 reduce 方法有扎实的理解,并能够自信地将其应用到您自己的项目中。

1. 加法和乘法:

reduce 方法非常适合对数组执行简单的数学运算。例如,我们可以使用 reduce 方法来计算数组中所有元素的和或积。

一个 n d \sum 和 \prod

// Summation
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a + i);

// Without initial value
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a + i, 5 );

// For clarity the above code is the same as 
[3, 5, 4, 3, 6, 2, 3, 4].reduce(function(a, i){return (a + i)}, 0 );

// Multiplication
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a * i);
Enter fullscreen mode Exit fullscreen mode

在这个例子中,我们可以省略初始值,因为它会获取数组中的第一个元素,但你也可以指定一个初始值来设置偏移量。

2. 找出数组中的最大值:

reduce 方法的另一个常见用途是查找数组中的最大值。通过指定初始值 -∞,我们可以将数组中的每个元素与累加器进行比较,并返回最大值。

[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => Math.max(a, i), -Infinity);
Enter fullscreen mode Exit fullscreen mode

作为替代方案,您也可以使用扩展运算符和 Math.max 内置方法。

Math.max(...[3, 5, 4, 3, 6, 2, 3, 4]);
Enter fullscreen mode Exit fullscreen mode

3. 连接不均匀数组

reduce 方法也可以用来连接数组,即使数组长度不同。在这个例子中,我们使用 map 方法遍历每个子数组,然后使用 reduce 方法将所有元素合并成一个字符串。

let data = [
  ["The","red", "horse"],
  ["Plane","over","the","ocean"],
  ["Chocolate","ice","cream","is","awesome"], 
  ["this","is","a","long","sentence"]
]
let dataConcat = data.map(item=>item.reduce((a,i)=>`${a} ${i}`))

// Result
['The red horse', 
'Plane over the ocean', 
'Chocolate ice cream is awesome', 
'this is a long sentence']
Enter fullscreen mode Exit fullscreen mode

4. 删除数组中的重复项:

reduce 方法也可以用来从数组中删除重复项。在这个例子中,我们检查当前值在累加器数组中是否有索引。如果没有,则将其添加到数组中。

let dupes = [1,2,3,'a','a','f',3,4,2,'d','d']
let withOutDupes = dupes.reduce((noDupes, curVal) => {
  if (noDupes.indexOf(curVal) === -1) { noDupes.push(curVal) }
  return noDupes
}, [])
Enter fullscreen mode Exit fullscreen mode

值得注意的是,也可以使用javascript set来实现此方法,该函数默认情况下只存储唯一值。

5. 验证括号

reduce 方法也可以用来验证字符串中的括号。在这个例子中,我们使用扩展运算符将字符串转换为数组,然后使用 reduce 方法遍历每个字符。如果字符是左括号,则累加器加一;如果是右括号,则累加器减一。最后,如果累加器值为 0,则表示括号匹配。

[..."(())()(()())"].reduce((a,i)=> i==='('?a+1:a-1,0);

// using a for loop
status=0
for i in string:
  if(i=="("):
    status=status+1
  elif(i==")"):
    status=status-1     
  if(status<0):
    return False
Enter fullscreen mode Exit fullscreen mode

6. 过滤和计数:

reduce 方法还可以用于过滤和统计数组中的元素数量。在这个例子中,我们使用 reduce 方法过滤掉所有非数字元素,然后统计剩余元素的数量。

let data = [1, 2, "a", "b", 3, "c", 4, "d"];
let filteredData = data.reduce((acc, curr) => {
  if (typeof curr === "number") {
    acc.push(curr);
  }
  return acc;
}, []);
console.log(filteredData); // [1, 2, 3, 4]
console.log(filteredData.length); // 4
Enter fullscreen mode Exit fullscreen mode

7. 按属性分组

reduce 方法还可以用于按特定属性对数组中的元素进行分组。在本例中,我们使用 reduce 方法按对象的“type”属性对对象数组进行分组。在每次迭代中,我们检查键是否存在;如果不存在,则创建一个新数组,然后将当前类型添加到该数组中,最后返回分组后的数组。

let data = [
  { type: "A", value: 1 },
  { type: "B", value: 2 },
  { type: "A", value: 3 },
  { type: "B", value: 4 },
  { type: "A", value: 5 },
];
let groupedData = data.reduce((acc, curr) => {
  if (!acc[curr.type]) {
    acc[curr.type] = [];
  }
  acc[curr.type].push(curr);
  return acc;
}, {});
console.log(groupedData); // { A: [ { type: 'A', value: 1 }, { type: 'A', value: 3 }, { type: 'A', value: 5 } ], B: [ { type: 'B', value: 2 }, { type: 'B', value: 4 } ] }
Enter fullscreen mode Exit fullscreen mode

8. 展平嵌套数组:

reduce 方法也可以用来展平嵌套数组。在这个例子中,我们使用 reduce 方法将一个数组的数组展平为一个单独的数组。

let data = [[1, 2], [3, 4], [5, 6]];
let flattenedData = data.reduce((acc, curr) => acc.concat(curr), []);
console.log(flattenedData); // [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

实现此目的的正确方法是直接使用 .flat 方法。

[ [3, 4, 5],
  [2, 5, 3],
  [4, 5, 6]
].flat();
Enter fullscreen mode Exit fullscreen mode

9. 统计元素的出现次数:

在这个例子中,我们使用 reduce 方法来统计数组中每个元素出现的次数。

let data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];
let countedData = data.reduce((acc, curr) => {
  if (!acc[curr]) {
    acc[curr] = 0;
  }
  acc[curr]++;
  return acc;
}, {});
console.log(countedData); // { 1: 1, 2: 2, 3: 3, 4: 4 }
Enter fullscreen mode Exit fullscreen mode

这就像同时进行地图绘制和过滤一样,我们过滤掉负数,提高正数。

10. 反转字符串

这里我们使用 reduce 方法来反转字符串,这不仅适用于字符串,也适用于任何对象。

const reverseStr = str=>[...str].reduce((a,v)=>v+a)
Enter fullscreen mode Exit fullscreen mode

奖金

11. 二进制转十进制

在这个例子中,我们可以用它来将二进制数转换为十进制数。
这里我们将字符串转换为数组,然后按顺序对数组进行平方运算,直到得到十进制数。

const bin2dec = str=>[...String(str)].reduce((acc,cur)=>+cur+acc*2,0)

// Long format for readability
const bin2dec = (str) => {
  return [...String(str)].reduce((acc,cur)=>{
    return +cur+acc*2
  },0)
}
Enter fullscreen mode Exit fullscreen mode

为了说明这一点,我们来看一个例子:
(10111)->1+(1+(1+(0+(1+0*2)*2)*2)*2)*2

最后,我们得出结论:reduce 方法是一种用途广泛且功能强大的工具,可以用来解决各种各样的问题。

欢迎访问我的 YouTube 频道ramgendeploy,喜欢的话记得订阅哦😄

文章来源:https://dev.to/ramgendeploy/learn-javascript-reduce-method-with-5-examples-128n