How to use the reduce Method In Javascript
The reduce method iterates over each element in the array and apply the callback function to each element and updating the accumulator accordingly. After iterating over all elements, the reduce method returns the final value of the accumulator, which represents the length of the array.
Example: This example uses reduce method to calculate the length of an array.
const arr = [1, 2, 3, 4, 5];
const length = arr.reduce((acc) => acc + 1, 0);
console.log(length);
Output
5
How to Find the Length of an Array in JavaScript ?
JavaScript provides us with several approaches to count the elements within an array. The length of an array lets the developer know whether an element is present in an array or not which helps to manipulate or iterate through each element of the array to perform some operation.
Table of Content
- Using the length Property
- Looping Through the Array
- Using forEach Method
- Using Spread Operator
- Conversion to String
- Using the reduce Method
Contact Us