帮你精通JS:神奇的array.reduce方法的10个案例( 二 )

callback
accumulator
currentValue
currentIndex
array
return value
first call
10
0
0
[0, 1, 2, 3, 4]
10
second call
10
1
1
[0, 1, 2, 3, 4]
11
third call
11
2
2
[0, 1, 2, 3, 4]
13
fourth call
13
3
3
[0, 1, 2, 3, 4]
16
fifth call
16
4
4
[0, 1, 2, 3, 4]
20
这种情况下reduce()返回的值是20 。
案例01. 数组里所有值的和var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {return accumulator + currentValue;}, 0);// 和为 6你也可以写成箭头函数的形式:
var total = [ 0, 1, 2, 3 ].reduce(( acc, cur ) => acc + cur,0);reduce的核心就是最终返回一个值,以一个值开始,以一个值结束 。
案例02. 累加对象数组里的值要累加对象数组中包含的值,必须提供初始值,以便各个item正确通过你的函数 。
var initialValue = https://www.isolves.com/it/cxkf/yy/js/2021-03-03/0;var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) {return accumulator + currentValue.x;},initialValue)console.log(sum) // logs 6你也可以写成箭头函数的形式:
var initialValue = https://www.isolves.com/it/cxkf/yy/js/2021-03-03/0;var sum = [{x: 1}, {x:2}, {x:3}].reduce((accumulator, currentValue) => accumulator + currentValue.x,initialValue);console.log(sum) // logs 6也可以操作其他数据结构 。
案例03. 将二维数组转化为一维var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {return a.concat(b);},[]);// flattened is [0, 1, 2, 3, 4, 5]你也可以写成箭头函数的形式:
var flattened = [[0, 1], [2, 3], [4, 5]].reduce( ( acc, cur ) => acc.concat(cur), []);案例04.计算数组中每个元素出现的次数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 }案例05. 按属性对object分类var people = [{ name: 'Alice', age: 21 },{ name: 'Max', age: 20 },{ name: 'Jane', age: 20 }];function groupBy(objectArray, property) {return objectArray.reduce(function (acc, obj) {var key = obj[property];if (!acc[key]) {acc[key] = [];}acc[key].push(obj);return acc;}, {});}var groupedPeople = groupBy(people, 'age');// groupedPeople is:// {//20: [//{ name: 'Max', age: 20 },//{ name: 'Jane', age: 20 }//],//21: [{ name: 'Alice', age: 21 }]// }案例06. 使用扩展运算符和initialValue绑定包含在对象数组中的数组// friends - 对象数组// where object field "books" - list of favorite booksvar friends = [{name: 'Anna',books: ['Bible', 'Harry Potter'],age: 21}, {name: 'Bob',books: ['War and peace', 'Romeo and Juliet'],age: 26}, {name: 'Alice',books: ['The Lord of the Rings', 'The Shining'],age: 18}];// allbooks - list which will contain all friends' books +// additional list contained in initialValuevar allbooks = friends.reduce(function(prev, curr) {return [...prev, ...curr.books];}, ['Alphabet']);// allbooks = [//'Alphabet', 'Bible', 'Harry Potter', 'War and peace',//'Romeo and Juliet', 'The Lord of the Rings',//'The Shining'// ] 
案例07. 数组去重注意: 如果你正在使用一个可以兼容Set 和 Array.from() 的环境,你可以使用let orderedArray = Array.from(new Set(myArray)); 来获得一个相同元素被移除的数组 。
let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']let 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]案例08. 按顺序运行Promise/** * Runs promises from array of functions that can return promises * in chained manner * * @param {array} arr - promise arr * @return {Object} promise object */function runPromiseInSequence(arr, input) {return arr.reduce((promiseChain, currentFunction) => promiseChain.then(currentFunction),Promise.resolve(input));}// promise function 1function p1(a) {return new Promise((resolve, reject) => {resolve(a * 5);});}// promise function 2function p2(a) {return new Promise((resolve, reject) => {resolve(a * 2);});}// function 3- will be wrApped in a resolved promise by .then()function f3(a) { return a * 3;}// promise function 4function p4(a) {return new Promise((resolve, reject) => {resolve(a * 4);});}const promiseArr = [p1, p2, f3, p4];runPromiseInSequence(promiseArr, 10).then(console.log);// 1200


推荐阅读