How to use the reduce() method In Javascript
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value. In this approach, the reduce() method is utilized to iterate over the array and build a new array based on certain conditions.
Syntax:
const newArray = originalArray.reduce((accumulator, currentValue[, index[, array]]) => {
// Your condition here
return accumulator;
}, initialValue);
Example: To demonstrate filtering the even number from the array using reduce method in JavaScript.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers
.reduce((accumulator, currentValue) => {
if (currentValue % 2 === 0) {
accumulator
.push(currentValue);
}
return accumulator;
}, []);
console.log(evenNumbers);
Output
[ 2, 4 ]
How to Filter an Array in JavaScript ?
Filtering an array in JavaScript involves selecting elements based on certain criteria. The selected elements form a new array. This operation is integral to tasks such as data manipulation, data processing, and displaying filtered results. The function tests each element in the array and includes it in the filtered array if it meets the criteria, otherwise it is excluded.
This operation is commonly used in JavaScript programming for tasks such as data manipulation, data processing, and displaying filtered results to users.
Table of Content
- Using the filter() method
- Using a for loop
- Using the reduce() method
Contact Us