- Home
- JavaScript
- JavaScript Array reduce() Meth ...
JavaScript Array reduce() Method
The JavaScript Array reduce() method is built-in array function that is used to “reduce” an array into a single value. Array reduce() method returns single value.
Array reduce() method does not change orignal array. It iterates over the elements of an array and collect a result based on specified callback function.
It takes two parameters: accumulator , initialvalue .
Here’s the basic syntax of the reduce() method:
array.reduce(callback, initialValue);
- array: The array you want to reduce.
callback: A function that contains code to perform that defines how the reduction should be performed.
- initialValue (optional): An initial value for the accumulator.. If not provided, the first element in the array will be used as the initial accumulator value.
Here’s a simple example of using reduce()
Find the sum of an array elements of numbers
//javascript reduce
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 15
In this example, the reduce() method adds each element of the numbers array to the accumulator, normally starting with an initial value of 0.
You can use reduce() for various purposes, such as finding the maximum or minimum value in an array, counting occurrences of specific elements, and more, by customizing the callback function to suit your needs.
Recent Post
Var keyword in C#
- May 8, 2024
- 4 min read
What is Cloud Computing ? Definition &
- April 2, 2024
- 4 min read
Devika – An Open-Source AI Software Engineer
- March 27, 2024
- 3 min read