How to use reduce function in JS

reduceis an array method in JavaScript that is used to accumulate all elements of the array and ultimately return a single value. It accepts a callback function as a parameter. This callback function can accept four parameters:

  1. Accumulator: The accumulator is the result of each callback function execution. It accumulates the accumulated value in each iteration.
  2. Current element: The element currently being processed in the array.
  3. Current index: The index of the current element in the array.
  4. Original array: reduceThe original array of the call.

reduceThere are two forms of methods, one only accepts a callback function, and the other can also accept an initial value as the second parameter.

Here is reducea basic usage example of :

const numbers = [1, 2, 3, 4, 5];

// 使用 reduce 对数组中的元素求和
const sum = numbers.reduce((accumulator, currentValue) => {
    
    
  return accumulator + currentValue;
}, 0); // 初始值为 0

console.log(sum); // 输出 15,因为 1 + 2 + 3 + 4 + 5 = 15

In this example, we use to sum the elements in an array reduce. numbersThe initial value 0is passed to the accumulator, and then the callback function adds the accumulator and the current element on each iteration, resulting in the final sum.

You can also provide no initial value, in which case reducethe first element of the array will be used as the initial value by default, and iteration will start from the second element. If the array is empty and no initial value is provided, an error will be thrown.

reduceis very versatile, you can use it to perform various accumulation operations, such as finding the maximum/minimum value, concatenating strings, calculating averages, etc. Depending on your needs, you can write appropriate logic in the callback function to achieve the required functionality.

PS: The following is a writing method used in my code (you can learn about my own notes on appsmitch)

const columns = inputData.fieldSource.reduce((prev:any,next:any,index:number)=>{
    
    
const {
    
     shouId,type } = next
prev[shouId] = {
    
    
 id:shouId,
 label:shouId,
 index:index,
 columnType:type,
 width:100,
}
return prev;
},{
    
    }
)

这里 fieldSource格式为  
fieldSource:[
{
    
    
	shouId:'code',
	type:'TEXTBOX'
},
{
    
    
	shouId:'delect',
	type:'TEXTBOX',
}
]
///
生成的结果为:
console.log(columns )
columns ={
    
    
code:{
    
    id:'code',label:'code',index:0,columnType:'TEXTBOX',width:100},
delect:{
    
    id:'delect',label:'delect',index:1,columnType:'TEXTBOX',width:100}
}

Guess you like

Origin blog.csdn.net/z2000ky/article/details/132729512