Usage of reduce in JavaScript

The usage of reduce() in JavaScript


foreword

This article mainly summarizes the usage of reduce(). It may be difficult to understand. You can read it several times, and then do it yourself.


1. First understand what is reduce

1. The reduce() method receives a function as an accumulator, and reduce executes the callback function for each element in the array in turn, excluding elements that are deleted or have never been assigned a value in the array. (I don’t understand, look down for a simple example)

语法:arr.reduce(callback,[initialValue])
callback:函数中包含四个参数
- previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
- currentValue (数组中当前被处理的元素)
- index (当前元素在数组中的索引)
- array (调用的数组)
initialValue (作为第一次调用 callback 的第一个参数。)

2. Examples

const arr = [1, 2, 3, 4, 5]
const sum = arr.reduce((prev, cur) => {
    
    
    return prev + cur
}, 0)
console.log(sum) // 15

0 here represents the default initial parameter for calling the callback function for the first time.
If it is 1 then the result will become 16

const arr = [1, 2, 3, 4, 5]
const sum = arr.reduce((prev, cur) => {
    
    
    return prev + cur
},1)
console.log(sum)//16

3. Of course, it can also be used in array objects

const scores = [
    {
    
    
        subject: 'java',
        score: 80
    },
    {
    
    
        subject: 'python',
        score: 80
    },
    {
    
    
        subject: 'Javascript',
        score: 80
    }
];
const sum = scores.reduce((prev, cur) => {
    
    
    return prev + cur.score
}, 0)
console.log(sum)

Do you feel that you understand some usage

2. Advanced usage

1. Array deduplication

var arr = [1,2,3,4,4,5,5]
var newArr = arr.reduce(function (prev, cur) {
    
    
    prev.indexOf(cur) === -1 && prev.push(cur);
    return prev;
},[]);

First, the initial parameter is an empty array, then use indexOf to determine whether there is an array in the array, and use the push method to add elements to the array

2. Convert a two-dimensional array into a one-dimensional array

var arr = [1, 2, 3, 4,[5, 6, 7]];
var res = arr.reduce((x, y) => x.concat(y), []);
console.log(res);

Summarize

If you have other methods, welcome to comment and discuss. If there are any mistakes, please correct them and accept them with an open mind.

Guess you like

Origin blog.csdn.net/qq_43205326/article/details/109729520