Array.reduce

2021-06-07  本文已影响0人  diviner_杨

reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

reducer 函数接收four个参数:

  1. Accumulator (acc) (累计器)
  2. Current Value (cur) (当前值)
  3. Current Index (idx) (当前索引)
  4. Source Array (src) (源数组)

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

数组累加等

const res1 = [0, 1, 2, 3, 4].reduce((prev, curr) => prev + curr ) 
const res2 = [0, 1, 2, 3, 4].reduce((prev, curr, currentIndex, array) => {
    return prev+ curr
}, 0)
console.log(res1 === res2 , res1, res2) // true 10 10

数组去重

const arr = [1, 1, 2, 2, 6 , 5 ,66]
const newArr= arr.reduce((pre, cur) => {
      if(!pre.includes(cur)){
           return pre.concat(cur)
       }else{
           return pre
       }
}, [])
console.log(newArr) // [1, 2, 6, 5, 66]
console.log(newArr.sort()) //  [1, 2, 5, 6, 66]

数组计数

const arr = ['星期一', '星期二', '星期三', '星期四', '星期四',  '星期五', '星期二', '星期一']
const newObj= arr.reduce((pre, cur ) => {
      if(cur in pre){
           pre[cur] ++
       }else{
           pre[cur] = 1
       }
    return pre
}, {}) //初始传入空对象

console.log(newObj) // {星期一: 2, 星期二: 2, 星期三: 1, 星期四: 2, 星期五: 1}

数组扁平化

const arr = [1, [2,3],[4,[7,8]]]

no.flat

console.log(arr.flat(Infinity)) //[1, 2, 3, 4, 7, 8]

no.正则

 const res2 =  JSON.stringify(arr).replace(/\[|\]/g, '')
console.log(res2.split(',')) //["1", "2", "3", "4", "7", "8"]

const res3 = JSON.parse('[' + res2 + ']')
console.log(res3) // [1, 2, 3, 4, 7, 8]

no.for

 const array = []
 const fn = (arr) =>{
   for (let i = 0; i < arr.length; i++) {
       if(Array.isArray(arr[i])){
            fn(arr[i])
       }else{
           array.push(arr[i])
       }
    }
}
fn(arr)
console.log(array) //[1, 2, 3, 4, 7, 8]

no.reduce

const newArr = (arr) =>{
   return arr.reduce((pre, cur)=>{
       return pre.concat(Array.isArray(cur) ? newArr(cur) : cur)
   }, [])
}
console.log(newArr(arr)) //[1, 2, 3, 4, 7, 8]

手写一个reduce

//放在数组原型下
Array.prototype.reduceArr =  function(fn, initValue){
    //判断是否为function
    if(Object.prototype.toString.call(fn) !== '[object Function]'){
        throw new Error('不是一个function')
    }
   
    let arr = this;//当前数组
    let initIndex;//初始下标
    let acc;//累加器
    //判断是否有第二个初始参数
    initIdnex = arguments.length === 0 ?  1 : 0;
    acc = arguments.length === 0 ? arr[0] : initValue;
    //遍历回调并返回出去
    for (let i = initIdnex; i < arr.length; i++) {
        acc = fn(acc,arr[i],i,arr)
    }
    return acc;
}
//实验
let arr = [1,2,3]
let arrRes1 = arr.reduceArr((pre, cur) => {
     return pre + cur   
}, 0)

console.log(arrRes1) // 6
let arrRes2 = arr.reduceArr((pre, cur) => {
     return pre + cur   
}, 1)

console.log(arrRes2) // 7
let arrRes3 = arr.reduceArr((pre, cur) => {
     return pre + cur   
}, 10)
console.log(arrRes3) // 16

更多

MDN reduce

上一篇下一篇

猜你喜欢

热点阅读