Array.prototype.reduce () is simple to use (Continued ...)

reduce()Performing one method of each element in the array 自定义of reducerfunction (in ascending order execution), summarizes the results of single return value

const array = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

const a = array.reduce(reducer);   // 1 + 2 + 3 + 4
console.log(a);   // 10

const b = array.reduce(reducer, 5);   // 5 + 1 + 2 + 3 + 4
console.log(b);   // 15

reducer Function receives four parameters:

  1. Accumulator (acc) (totalizer)
  2. Current Value (cur) (current value)
  3. Current Index (idx) (current index)
  4. Source Array (src) (source array)

The return value of your reducer function assigned to the accumulator, the return value is remembered in each iteration of an array, and finally become the ultimate single result value


grammar

arr.reduce(callback(acc, cur, idx, src), initialValue)

parameter:

callback

  • accumulatorAccumulator accumulated callback return value; it is a cumulative value returned by a previous call to the callback, or initialValue(see below)
  • currentValue Elements in the array being processed
  • index (可选)Index of the current element in the array being processed. If provided initialValue, the starting index number is 0, 1 or starting from index
  • array (可选)Call reduce()array

initialValue (optional)

  • As the first argument when the first call to the callback function values. If no initial value, the first element in the array will be used. On an empty array with no initial value will reduce call error

return value

Result of the function integration process


application

Computing array of all the values ​​and

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

console.log(sum)

The cumulative value of the object in the array

const arr = [{x: 1}, {x: 2}, {x: 3}]
let sum = arr.reduce(
  (acc, cur)=> acc + cur.x,
  0
)

console.log(sum)

Two-dimensional array into a one-dimensional array

const arr = [[0, 1], [2, 3], [4, 5]]
let change = arr.reduce(
  (acc, cur)=> acc.concat(cur),
  []
)

console.log(change)

The number of calculations for each array element appears

const names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']
let count = names.reduce(
  (allnames, name)=> {
    if(name in allnames) {
      allnames[name]++
    }else {
      allnames[name] = 1
    }
    return allnames
  },
  {}
)

console.log(count)
// console

[object Object] {
  Alice: 2,
  Bob: 1,
  Bruce: 1,
  Tiff: 1
}

By attribute object classification

const people = [
  { name: 'Alice', age: 21 },
  { name: 'Max', age: 20 },
  { name: 'Jane', age: 20 }
];

let groupBy = (all, select)=> {
  return all.reduce(
    (acc, obj)=> {
      let key = obj[select]
      if(!acc[key]) {
        acc[key] = []
      }
      acc[key].push(obj)
      return acc
    }, {}
  )
}

let groupedPeople = groupBy(people, 'age')

console.log(groupedPeople)
// console

{ 
  20: [
    { name: 'Max', age: 20 }, 
    { name: 'Jane', age: 20 }
    ], 
  21: [
    { name: 'Alice', age: 21 }
  ] 
}

Extended arrays initialValue bind operator and contained in the object array

const 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(
  (acc, cur)=> [...acc, ...cur.books], 
  []
);

console.log(allbooks);
// console

["Bible", "Harry Potter", "War and peace", "Romeo and Juliet", "The Lord of the Rings", "The Shining"]

Deduplication Array

const arr = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'];

let newArr = arr.reduce(
  (acc, cur)=> {
    if(acc.indexOf(cur) === -1) {
      acc.push(cur)
    }
    return acc
  }, []
)

console.log(newArr)   // ["a", "b", "c", "e", "d"]
// 同上方法,判断 acc 数组里有没有 cur ,没有就往里加

let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];

let newArr = arr.sort().reduce(
  (acc, cur)=> {
    if(acc.indexOf(cur) === -1) {
      acc.push(cur)
    }
    return acc
  }, []
)

console.log(newArr)   // [1, 2, 3, 4, 5]


// 判断 acc 初始值为空,或者 acc 最后的值不为 cur (arr数组中最后一项)

let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];

let result = arr.sort().reduce((init, current) => {
    if(init.length === 0 || init[init.length-1] !== current) {
        init.push(current);
    }
    return init;
}, []);

console.log(result);   // [1,2,3,4,5]

In order to run Promise

let runPromiseInSequence = (arr, input) => arr.reduce(
  (promiseChain, currentFun) => promiseChain.then(currentFun),
  Promise.resolve(input)
)

let p1 = (a) => (new Promise((res, rej)=> {
  res(a*5)
}))

let p2 = (a) => (new Promise((res, rej)=> {
  res(a*2)
}))

let f3 = (a) => a * 3

let f4 = (a) => a * 4

const promiseArr = [p1, p2, f3, f4]

runPromiseInSequence(promiseArr, 10)
  .then(console.log)   // 1200
Published 23 original articles · won praise 0 · Views 571

Guess you like

Origin blog.csdn.net/JIANLI0123/article/details/103390955