The Reduce Method In JS: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the The Reduce Method In JS.
The Reduce Method In JS
The reduce method in JavaScript is a built-in function on the Array object that allows you to apply a function to each element in the array and reduce it to a single value.
The function takes two arguments: an accumulator (which accumulates the result of the callback function) and the current value.
The reduce method can be used for tasks such as computing the sum of an array of numbers, concatenating an array of strings, or flattening an array of arrays.
Syntax:
array.reduce(function(accumulator, currentValue, currentIndex, array) {
return accumulator;
}, initialValue);
Where:
function
is the callback function that will be executed for each element in the array.accumulator
is the accumulator value that accumulates the result of the callback function.currentValue
is the current value being processed in the array.currentIndex
is the index of the current value being processed in the array.array
is the original array thatreduce
was called upon.initialValue
is the initial value of the accumulator. If not provided, the first element in the array will be used as the initial value.
Here’s an example of using the reduce
method to calculate the sum of an array of numbers:
Reduce Method To Calculate The Sum Of An Array Of Numbers
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum);
Output
15
And here’s an example of using the reduce
method to concatenate an array of strings:
Reduce Method To Concatenate An Array Of Strings
let words = ['Hello', 'World'];
let sentence = words.reduce(function(accumulator, currentValue) {
return accumulator + ' ' + currentValue;
}, '');
console.log(sentence);
Output
'Hello World'
And finally, here’s an example of using the reduce
method to flatten an array of arrays:
Reduce Method To Flatten An Array Of Arrays
let nestedArray = [[0, 1], [2, 3], [4, 5]];
let flattenArray = nestedArray.reduce(function(accumulator, currentValue) {
return accumulator.concat(currentValue);
}, []);
console.log(flattenArray);
Output
[0, 1, 2, 3, 4, 5]
Conclusion
If you liked this post The Reduce Method In JS, then please share this with your friends and make sure to bookmark this website for more awesome content.