返回

深度剖析 JS Array.prototype.reduce()

前端





作为一名技术博客创作专家,我将以独树一帜的观点向您展现 JavaScript Array.prototype.reduce() 方法的奥妙。

## reduce() 方法概述
reduce() 方法是 JavaScript 数组内置的方法之一,它可以将数组中的元素逐个累加,最终返回一个累积值。reduce() 方法接收两个参数:一个 callback 函数和一个可选的初始值。

## 回调函数
callback 函数是一个用于对数组中的每个元素进行处理的函数,它接收四个参数:

- accumulator:累加器,累加回调的返回值。
- currentValue:当前元素的值。
- index:当前元素的索引。
- array:数组本身。

## 初始值
初始值是 reduce() 方法的可选参数,如果提供了初始值,则累加器的初始值将是初始值,否则累加器的初始值将是数组的第一个元素。

## reduce() 方法的应用场景
reduce() 方法在 JavaScript 中有着广泛的应用场景,以下是一些常见的应用场景:

- 数组求和
- 数组最大值/最小值查找
- 数组去重
- 展开多维数组
- 对象转换
- 数组分组

## reduce() 方法的示例代码
为了更好地理解 reduce() 方法的使用,这里提供一些示例代码:

// 数组求和
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(sum); // 15

// 数组最大值/最小值查找
const max = numbers.reduce((accumulator, currentValue) => Math.max(accumulator, currentValue));
console.log(max); // 5

const min = numbers.reduce((accumulator, currentValue) => Math.min(accumulator, currentValue));
console.log(min); // 1

// 数组去重
const uniqueNumbers = numbers.reduce((accumulator, currentValue) => {
if (!accumulator.includes(currentValue)) {
accumulator.push(currentValue);
}
return accumulator;
}, []);
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

// 展开多维数组
const multidimensionalArray = [[1, 2], [3, 4], [5, 6]];
const flatArray = multidimensionalArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
console.log(flatArray); // [1, 2, 3, 4, 5, 6]

// 对象转换
const users = [
{ name: 'John Doe', age: 25 },
{ name: 'Jane Doe', age: 30 },
{ name: 'Peter Smith', age: 35 }
];
const userObject = users.reduce((accumulator, currentValue) => {
accumulator[currentValue.name] = currentValue.age;
return accumulator;
}, {});
console.log(userObject); // { 'John Doe': 25, 'Jane Doe': 30, 'Peter Smith': 35 }

// 数组分组
const products = [
{ name: 'Product 1', category: 'Electronics' },
{ name: 'Product 2', category: 'Clothing' },
{ name: 'Product 3', category: 'Electronics' },
{ name: 'Product 4', category: 'Clothing' },
{ name: 'Product 5', category: 'Home & Kitchen' }
];
const groupedProducts = products.reduce((accumulator, currentValue) => {
if (!accumulator[currentValue.category]) {
accumulator[currentValue.category] = [];
}
accumulator[currentValue.category].push(currentValue);
return accumulator;
}, {});
console.log(groupedProducts);