Eloquent JavaScript - Array.prototype.reduce()方法解释

198 阅读2分钟

arr.reduce()方法解释

Reference链接

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value. 也就是说,arr.reduce()这个方法会用reducer()函数处理arr的每一个element。 下面我们来分析Reference给出的这个例子:

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
  1. array1.reduce(reducer)reducer这个函数会对array1的每一个元素进行处理。reducer函数把array1数组里的每一个元素会放在currentValue的位置进行处理,并将处理后的结果保存在accumulator里面。
  2. reducer这个函数有两个参数,一个是accumulator,一个是currentValue。当reducer处理完所有元素,accumulator就保存着array1.reduce(reducer)的最终结果。
  3. array1.reduce(reducer)array1.reduce(reducer, 5)的区别在哪里?区别在于后者提供了一个初始值(initialValue)5,这样accumulator的初始值等于这个initialValue,currentValue的值等于array1的第一个元素(array1[0])。前者,因为没有提供初始值,accumulator的初始值就等于array1[0]currentValue等于array1[1]。这就是是否有提供initialValue的区别。
  4. 个人觉得,理解的重点在于知道,accumulator保存的是结果,currentValue的值等于数组的元素。

arr.reduce()练习

Flattening

Use the reduce method in combination with the concat method to “flatten” an array of arrays into a single array that has all the elements of the original arrays.
我写的代码是:

function flatten(arr) {
    return arr.reduce((a, b) => a.concat(b)); 
} 

let arrays = [[1, 2, 3], [4, 5], [6]]; 
console.log(flatten(arrays)); 
// 如果不写flatten那个函数,可以直接写:console.log(arrays.reduce((a, b) => a.concat(b))); 
// 输出的结果是[1, 2, 3, 4, 5, 6]

arr.reduce((a, b) => a.concat(b))这一行代码,function reducer = (a, b) => a.concat(b)
因为没有提供初始值,那么a的初始值是[1, 2, 3],b的初始值是[4, 5]
我们也可以提供一个初始值(空数组):arr.reduce((a, b) => a.concat(b), [])。那么a的初始值就是[],b的初始值就是[1, 2, 3]
如果我们提供的初始值是[0]arr.reduce((a, b) => a.concat(b), [0]),那么最后的结果就是[0, 1, 2, 3, 4, 5, 6]

Array.prototype.flat()

reduce + concat + isArray + recursivity

const arr = [1, 2, [3, 4, [5, 6]]];

// to enable deep level flatten use recursion with reduce and concat
function flatDeep(arr, d = 1) {
   return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [])
                : arr.slice();
};

flatDeep(arr, Infinity);
// [1, 2, 3, 4, 5, 6]

Array.prototype.some()

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.

const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true