一、什麼是 reduce() ? reduce() 方法對數組中的每個元素執行一個升序執行的 reducer 函數,並將結果彙總為單個返回值 const array1 = [1, 2, 3, 4]; const reducer = (accumulator, currentValue) => acc ...
一、什麼是 reduce() ?
reduce() 方法對數組中的每個元素執行一個升序執行的 reducer 函數,並將結果彙總為單個返回值
const array1 = [1, 2, 3, 4]; const reducer = (accumulator, currentValue) => accumulator + currentValue; // 1 + 2 + 3 + 4 console.log(array1.reduce(reducer)); // 輸出: 10 // 5 + 1 + 2 + 3 + 4 console.log(array1.reduce(reducer, 5)); // 輸出: 15
二、數組中 reduce 方法的參數
1、第一個參數:reducer 函數
其中,reducer 函數又有四個參數:
- Accumulator (acc) (累計器)
- Current Value (cur) (當前值)
- Current Index (idx) (當前索引)
- Source Array (src) (源數組)
2、第二個參數(可選):initialValue
代表傳遞給函數的初始值
// 不傳第二個參數的情況 var numbers = [1, 2, 3, 4] function myFunction(item) { let result = numbers.reduce(function (total, currentValue, currentIndex, arr) { console.log(total, currentValue, currentIndex, arr) return total + currentValue }) return result } myFunction(numbers)
輸出:
可以看到如果不傳第二個參數 initialValue,則函數的第一次執行會將數組中的第一個元素作為 total 參數返回。一共執行3次
下麵是傳遞第二個參數的情況:
// 不傳第二個參數的情況 var numbers = [1, 2, 3, 4] function myFunction(item) { let result = numbers.reduce(function (total, currentValue, currentIndex, arr) { console.log(total, currentValue, currentIndex, arr) return total + currentValue }, 10) return result } myFunction(numbers)
輸出:
如果傳了第二個參數 initialValue,那麼第一次執行的時候 total 的值就是傳遞的參數值,然後再依次遍曆數組中的元素。執行4次
總結:如果不傳第二參數 initialValue,那麼相當於函數從數組第二個值開始,並且將第一個值最為第一次執行的返回值,如果傳了第二個參數 initialValue,那麼函數從數組的第一個值開始,並且將參數 initialValue 作為函數第一次執行的返回值
三、應用場景
1、數組裡所有值的和
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) { return accumulator + currentValue; }, 0); // 和為 6
2、累加對象數組裡的值
var initialValue = 0; var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) { return accumulator + currentValue.x; },initialValue) console.log(sum) // logs 6
3、將二維數組轉化為一維
var flattened = [[0, 1], [2, 3], [4, 5]].reduce( function(a, b) { return a.concat(b); }, [] ); // flattened is [0, 1, 2, 3, 4, 5]
4、計算數組中每個元素出現的次數
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']; var countedNames = names.reduce(function (allNames, name) { if (name in allNames) { allNames[name]++; } else { allNames[name] = 1; } return allNames; }, {}); // countedNames is: // { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
5、數組去重
var myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']; var myOrderedArray = myArray.reduce(function (accumulator, currentValue) { if (accumulator.indexOf(currentValue) === -1) { accumulator.push(currentValue); } return accumulator }, []) console.log(myOrderedArray);
let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4]; let result = arr.sort().reduce((init, current) => { if(init.length === 0 || init[init.length-1] !== current) { init.push(current); } return init; }, []); console.log(result); //[1,2,3,4,5]