In JavaScript, we can reduce an array of values to a single value through the use of the reduce()
method. The reduce() method applies a callback function to each element of the array from left to right, allowing us to accumulate a value as we iterate through the array.
Syntax:
index.tsx48 chars2 lines
The callback_function
takes two arguments, the accumulator
and the current_value
.
Here is an example of using reduce() to find the sum of all elements in an array of numbers:
index.tsx175 chars8 lines
In the above example, the initial_value
is set to 0
. On the first iteration of the reduce() method, 0
is passed as the accumulator
value and the first element of the array (10
) is passed as the current_value
. The callback function adds these two values together and returns the result (10
). On the second iteration, the accumulator
value is set to 10
(result of previous iteration) and the current_value
is 20
. This continues throughout the array, and finally, we get the total sum of all the elements in the array.
We can also use reduce() to find the maximum or minimum value of an array:
index.tsx234 chars12 lines
Here, the callback_function
checks if the accumulator
value is greater than the current_value
. If it is, it returns the accumulator
value; otherwise, it returns the current_value
. This way, we can determine the maximum value of the array. Similarly, we can determine the minimum value of the array by checking if accumulator
is less than current_value
.
gistlibby LogSnag