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. Grammararray.reduce(function(prev, cur, index, arr), initialValue) //Shorthand for easy explanation arr.reduce(callback,[initialValue]) Parameter meaning:
2. Example parsing initialValue parameterLet’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 reduceOf 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 SummarizeThis 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:
|
<<: mysql 8.0.15 winx64 decompression version graphic installation tutorial
>>: Detailed tutorial on how to monitor Nginx/Tomcat/MySQL using Zabbix
This article example shares the specific code of ...
Dockerfile is a text file used to build an image....
This article is used to record the installation o...
background Today, I was browsing CodePen and saw ...
Preface Recently I started using robot framework ...
What is a file system We know that storage engine...
What are slots? We know that in Vue, nothing can ...
Preface In order to ensure the consistency and in...
Write a SQL first SELECT DISTINCT from_id FROM co...
Preface During project development, due to differ...
We all know that the performance of applications ...
Types of Indexes in MySQL Generally, they can be ...
This article mainly introduces CSS circular hollo...
<br />Original URL: http://www.lxdong.com/po...
<br /> English original: http://desktoppub.a...