关于Array中reduce的实际应用
Posted huangbohang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于Array中reduce的实际应用相关的知识,希望对你有一定的参考价值。
// 数组中所有值求和
let arr = [0, 1, 2, 3]
let sum = arr.reduce((accumulator, currentValue)=> {
return accumulator + currentValue;
}, 0);
console.log(sum)
// 二位数组转化为一维数组
let array2 = [[0, 1], [2, 3], [4, 5]]
let array = array2.reduce((first, last) => {
return first.concat(last)
}, [])
console.log(array)
//计算数组中每个元素出现的次数
let names = ['hbh', 'zz', 'yd', 'wan', 'hbh', 'hbh', 'wan', 'zz']
let obj = {}
names.reduce((before, after) => {
before[after] ? before[after]++ : before[after] = 1
return before
}, obj)
console.log(obj)
// 根据属性对object进行分类
let people = [
{name: 'Alice', age: 21},
{name: 'Max', age: 20},
{name: 'Jane', age: 20}
]
let group = {}
people.reduce(((before, after) => {
before[after.age] ? before[after.age].push(after) : before[after.age] = [after]
return before
}), group)
console.log(group)
上述内容源自mdn中reduce中例子,https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
以上是关于关于Array中reduce的实际应用的主要内容,如果未能解决你的问题,请参考以下文章