JavaScript Array reduce() MethodThe reduce() method reduces the given array into a single value by executing a reducer function. The user implements the reducer function that works on every element present in the array. Reducer FunctionThe reducer function is the user implemented code. It uses the following four arguments to perform its task:
SyntaxParametercallback: The main is the callback function that executes for each element, excluding the first, if no initialValue is specified. The callback function undertakes the following four arguments:
initialValue: It is the first argument value used in the first invocation of the callback function. ReturnIt returns a single value as an output. Points to note:
Thus, it is safe and good to provide the initial value. JavaScript Array reduce() Method ExampleLet's implement some examples to understand better: Example1 Here's a simple example to sum up the array elements and display the output. Test it NowOutput: Example2 Here's an example to display the difference of the array elements using reduce() method. Test it NowOutput: Example3 Here's an example to total the array elements using the arrow function. Test it NowOutput: Example4 When the array contain a single value only. Test it NowOutput: Thus, in presence of a single array element, there is no need to create a callback function. Also, because when an array contain a single element, the callback is not invoked. We can perform several examples using the array reduce() method.
Next TopicJavaScript Array
|