JavaScript array reduce() method syntax and example analysis

JavaScript array reduce() method syntax and example analysis

Preface

The reduce() method receives a function as an accumulator, and each value in the array (from left to right) is reduced to a single value.

reduce executes the callback function in sequence for each element in the array, excluding elements that have been deleted or never assigned in the array, and accepts four parameters: the initial value (or the return value of the previous callback function), the current element value, the current index, and the array on which reduce is called.

Among Javascript array methods, reduce is often overlooked compared to commonly used iteration methods such as map, filter, forEach, etc. Today, let's explore the wonderful uses of reduce in our actual development. Let's start with the reduce syntax.

1. Grammar

array.reduce(function(prev, cur, index, arr), initialValue)
//Shorthand for easy explanation arr.reduce(callback,[initialValue])

Parameter meaning:

callback (a function to execute for each value in the array, containing four parameters)
1. previousValue (the value returned by the last callback call, or the initial value provided)
2. currentValue (the element currently being processed in the array)
3. index (index of the current element in the array)
4. array (array on which reduce is called)
initialValue (as the first parameter of the first callback call.) Similar to setting the initial value

2. Example parsing initialValue parameter

Let’s look at the first example:

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 results:
//1 2 1
//3 3 2
//6 4 3
//[1, 2, 3, 4] 10

It can be seen here that the index in the above example starts from 1, and the value of prev for the first time is the first value of the array. The array length is 4, but the reduce function loops 3 times.

Let’s look at the second example:

var arr = [1, 2, 3, 4];
var sum = arr.reduce(function(prev, cur, index, arr) {
    console.log(prev, cur, index);
    return prev + cur;
},0) //Note that the initial value is set here console.log(arr, sum);
//Print results:
//0 1 0
//1 2 1
//3 3 2
//6 4 3
//[1, 2, 3, 4] 10

In this example, the index starts at 0, the first value of prev is the initial value 0 we set, the array length is 4, and the reduce function loops 4 times.

Conclusion: If initialValue is not provided, reduce will execute the callback method starting from index 1, skipping the first index. If initialValue is provided, start at index 0.

Note: What happens if the array is empty when using reduce?

var arr = [];
var sum = arr.reduce(function(prev, cur, index, arr) {
    console.log(prev, cur, index);
    return prev + cur;
})
//Error, "TypeError: Reduce of empty array with no initial value"

But if we set the initial value, there will be no error, as follows:

var arr = [];
var sum = arr.reduce(function(prev, cur, index, arr) {
    console.log(prev, cur, index);
    return prev + cur;
},0)
console.log(arr, sum); // [] 0

So in general it is usually safer to provide an initial value

3. Simple usage of reduce

Of course, the simplest one is the array summation and product that we often use.

var arr = [1, 2, 3, 4];
var sum = arr.reduce((x,y)=>x+y)
var mul = arr.reduce((x,y)=>x*y)
console.log( sum ); // sum, 10
console.log( mul ); //Find the product, 24

4. Advanced usage of reduce

(1) Count the number of times each element appears in an array

let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
let nameNum = names.reduce((pre,cur)=>{
  if (cur in pre) {
    pre[cur]++
  }else{
    pre[cur] = 1 
  }
  return pre
},{})
console.log(nameNum); //{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}

(2) Array deduplication

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); // [1, 2, 3, 4]

(3) Convert a two-dimensional array into a one-dimensional array

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) Convert a multidimensional array into a one-dimensional array

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)); //[0, 1, 2, 3, 4, 5, 6, 7]

(4) Summing the attributes in an object

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

Summarize

This is the end of this article about JavaScript array reduce() method. For more related JS array reduce() method content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Analysis of the principle and usage skills of JS array reduce() method
  • Detailed explanation of JS array Reduce() method and advanced techniques
  • JavaScript Array reduce() Method

<<:  mysql 8.0.15 winx64 decompression version graphic installation tutorial

>>:  Detailed tutorial on how to monitor Nginx/Tomcat/MySQL using Zabbix

Recommend

Native js implements custom scroll bar component

This article example shares the specific code of ...

Dockerfile text file usage example analysis

Dockerfile is a text file used to build an image....

Installation of Docker CE on Ubuntu

This article is used to record the installation o...

JS uses clip-path to implement dynamic area clipping function

background Today, I was browsing CodePen and saw ...

How to use boost.python to call c++ dynamic library in linux

Preface Recently I started using robot framework ...

Detailed explanation of MySQL file storage

What is a file system We know that storage engine...

Detailed analysis of the usage and application scenarios of slots in Vue

What are slots? We know that in Vue, nothing can ...

In-depth explanation of the locking mechanism in MySQL

Preface In order to ensure the consistency and in...

The difference and reasons between the MySQL query conditions not in and in

Write a SQL first SELECT DISTINCT from_id FROM co...

CSS specification BEM CSS and OOCSS sample code detailed explanation

Preface During project development, due to differ...

Summary of situations where MySQL indexes will not be used

Types of Indexes in MySQL Generally, they can be ...

Implementation of CSS circular hollowing (coupon background image)

This article mainly introduces CSS circular hollo...

Newbies quickly learn the steps to create website icons

<br />Original URL: http://www.lxdong.com/po...

The grid is your layout plan for the page

<br /> English original: http://desktoppub.a...