reduce的用法

1、求和

[ 0, 1, 2, 3 ].reduce( ( acc, cur ) => acc + cur, 0 )
// 6

2、数组扁平化

[[0, 1], [2, 3], [4, 5]].reduce( ( acc, cur ) => acc.concat(cur), [] )
// [0, 1, 2, 3, 4, 5]

3、计算数组中每个值出现的次数

var str = 'abcdaabc';
var a = str.split('').reduce(function(acc, cur) {
    acc[cur] ? acc[cur] ++ : acc[cur] = 1
    return acc;
}, {})
console.log(a)
// { a: 3, b: 2, c: 2, d: 1 }

4、对象数组的连接

var 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 }
]
var allbooks = friends.reduce((prev, curr) => [...prev, ...curr.books], ["Alphabet"])
console.log(allbooks)
// ["Alphabet", "Bible", "Harry Potter", "War and peace",  "Romeo and Juliet", "The Lord of the Rings", "The Shining"]

5、找到一个数字数组中数值最小的元素的位置

var arr = [ 3, 2, 1, 5, 4, 7, 8, 10, 6, 9 ]
var b = arr.reduce((prev, curr, i) => curr < arr[prev] ? i : prev, 0)
console.log(b)
// 2

扩展

reduceRight() 方法接受一个函数作为累加器(accumulator),让每个值(从右到左,亦即从尾到头)缩减为一个值。(与 reduce() 的执行方向相反)

mode_edit