reduce巧用

reduce巧用

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);

四、按属性对 object 分类

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')

五、使用扩展运算符和 initialValue 绑定包含在对象数组中的数组

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)

你可能感兴趣的:(前端,javascript,开发语言,ecmascript)