1.求和
2.累计出现次数
3.二维数组扁平一维数组
4.按属性对 object 分类
5.使用扩展运算符和 initialValue 绑定包含在对象数组中的数组
6.数组去重
var number = [{num:45},{num:4} , {num:9}, {num:16}, {num:25}];
let initialValue = 0
// 求和
var sum = number.reduce(myFunction,initialValue);
function myFunction(total, value, index, array) {
return total + value.num;
}
console.log(sum);
var numbers = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']
var sum1 = numbers.reduce(myFunction1,{})
function myFunction1(total,value){
if (value in total) {
total[value]++
} else {
total[value]=1
}
return total
}
console.log(sum1);
var numbers = [[0,1],[9,12],[8,2]]
var arr = numbers.reduce(getArry,[])
function getArry (total,value) {
return total.concat(value)
}
console.log(arr);
let people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
];
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
let key = obj[property]
if (!acc[key]) {
acc[key] = []
}
acc[key].push(obj)
return acc
}, {})
}
let groupedPeople = groupBy(people, 'age')
let 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
}]
let allbooks = friends.reduce(function(previousValue, currentValue) {
return [...previousValue, ...currentValue.books]
}, ['Alphabet'])
let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
let myArrayWithNoDuplicates = myArray.reduce(function (previousValue, currentValue) {
if (previousValue.indexOf(currentValue) === -1) {
previousValue.push(currentValue)
}
return previousValue
}, [])
console.log(myArrayWithNoDuplicates)