How to use reduce () Method In Javascript
In this method we will use reduce() method. In this method we need to pass a callback function which takes four arguments. Accumulator(acc), Current value (curr) ,Current Index(optional), Source Array(optional). This method iterates through each element of the array and then callback function is called for each element. The accumulator will calculate the new value for accumulator based on the current element and its current value.
Example: To demonstrate using the `reduce` method to accumulate the sum of elements in a given array.
Javascript
function sumArray(arr) { return arr.reduce( function (acc, curr) { return acc + curr; }, 0); } const arr = [2.3, 4.7, 4, 3]; console.log( "Input:" , arr); console.log( "Output:" , sumArray(arr)); |
Input: [ 2.3, 4.7, 4, 3 ] Output: 14
Time complexity: O(N)
Space complexity: O(1)
How to find the Sum of an Array of Numbers in JavaScript ?
Array in JavaScript is a data structure that is used to store a list of data. It is a contiguous block of memory which is used to store the data. As it is contiguous in memory we can access its elements in constant time.
There are several different methods for finding the sum of an array of numbers using JavaScript which are as follows:
Table of Content
- Using for Loop
- Using reduce () Method
- Using the eval() function
Contact Us