JavaScript reduce usage details

1. Introduction to reduce grammar

array.reduce((prev, item, index, arr)=> {
    
    
    /***/
}, initialValue)

Parameters:
parameter one callback function, which contains four parameters:

prev If initialValue is provided, it is; if initialValue is provided, it is the first item of the array
item The array element currently being processed by the array loop
index the index of the current currentValue
array The array on which to perform the reduce operation

The second parameter initialValue is the initial value, the initial value can be provided or not provided. Provide an initial value, item starts from the first item of the array, if no initial value is provided, item starts to execute from the second item, and the corresponding first prev is the value of the first item in the array Return value
:

Return the last execution result

Two, example analysis

let arr = ['h','i','n','a']
let str = arr.reduce((prev, item, index, arr)=> {
    
    
    console.log(prev, item, index, arr)
    return prev + item
}, 'C')
console.log(str) // China
var arr = [1, 2, 3, 4];
var sum = arr.reduce(function (prev, cur, index, arr) {
    
    
  console.log(prev, cur, index);
  return prev + cur;
});
console.log(arr, sum);

print result

1 2 1
3 3 2
6 4 3
[ 1, 2, 3, 4 ] 10

3. Matters needing attention

  1. reduce is a method for accumulating operations on arrays, and return must be added to return the data of the accumulation operation. In this way, prev can get the result of the last execution, otherwise it is undefined

  2. When the reduce operation is performed on an empty array and the initial value is not provided, the reduce will report an error. The error message is as follows:
    insert image description here

4. Specific use

1. Array deduplication

let arr = [1, 2, 2, 2, 3, 3, 4, undefined, undefined, null]
arr.reduce((prev, item) => {
    
    
    return prev.includes(item) ? prev : prev.concat(item);
}, [])
 
// [1, 2, 3, 4, undefined, null]
let arr = [1,2,3,4,4,1]
let newArr = arr.reduce((pre,cur)=>{
    
    
    if(!pre.includes(cur)){
    
    
      return pre.concat(cur)
    }else{
    
    
      return pre
    }
},[])
console.log(newArr);

2. Array flattening multi-dimensional to one-dimensional
array dimensionality reduction

let arr = [0,[1],[2, 3],[4, [5, 6, 7]]];
let reduceArray = function (arr) {
    
    
    return arr.reduce((prev, item) => {
    
    
        return prev.concat(Array.isArray(item) ? reduceArray(item) : item)
    }, [])
}
reduceArray(arr)
 
//[0, 1, 2, 3, 4, 5, 6, 7]
let arr = [[0, 1], [2, 3], [4,[5,6,7]]]
const newArr = function(arr){
    
    
   return arr.reduce((pre,cur)=>pre.concat(Array.isArray(cur)?newArr(cur):cur),[])
}
console.log(newArr(arr)); 

2D down to 1D

let arr = [[0, 1], [2, 3], [4, 5]]
let newArr = arr.reduce((pre,cur)=>{
    
    
    return pre.concat(cur)
},[])
console.log(newArr); 

打印结果[0, 1, 2, 3, 4, 5]

3. Array accumulation

let arr = [1, 2, 3, 4]
arr.reduce((prev, item) => {
    
    
    return prev + item;
})
 
// 10

4. Count the number of occurrences of each element in the array

var arr = ["one", "two", "three", "six", "four", "five", "six"];

var newArr = arr.reduce((pre, cur) => {
    
    
  console.log(cur, pre);
  if (cur in pre) {
    
    
    pre[cur]++;
  } else {
    
    
    pre[cur] = 1;
  }
  return pre;
}, {
    
    });//这里注意初始值要默认赋予空对象,不然会报错
console.log(newArr);

print result

打印结果
one {
    
    }
two {
    
     one: 1 }
three {
    
     one: 1, two: 1 }
six {
    
     one: 1, two: 1, three: 1 }
four {
    
     one: 1, two: 1, three: 1, six: 1 }
five {
    
     one: 1, two: 1, three: 1, six: 1, four: 1 }
six {
    
     one: 1, two: 1, three: 1, six: 1, four: 1, five: 1 }
{
    
     one: 1, two: 1, three: 1, six: 2, four: 1, five: 1 }

5. Object attribute summation

var result = [
    {
    
    
        subject: 'math',
        score: 10
    },
    {
    
    
        subject: 'chinese',
        score: 20
    },
    {
    
    
        subject: 'english',
        score: 30
    }
];
 
var sum = result.reduce(function(prev, cur) {
    
    
    return cur.score + prev;
}, 0);
console.log(sum) 

打印结果	60

Guess you like

Origin blog.csdn.net/m0_44973790/article/details/128828867