reduce array in javascript

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.tsx
array.reduce(callback_function, initial_value);
48 chars
2 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.tsx
const numbers = [10, 20, 30, 40];

const sum = numbers.reduce((accumulator, current_value) => {
  return accumulator + current_value;
}, 0);

console.log(sum); // Output: 100
175 chars
8 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.tsx
const numbers = [5, 10, 15, 20];

const max = numbers.reduce((accumulator, current_value) => {
  if (accumulator > current_value) {
    return accumulator;
  } else {
    return current_value;
  }
});

console.log(max); // Output: 20
234 chars
12 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