reduce in javascript

One way to reduce an array to a single value is by using the reduce() method in javascript. The reduce() method takes a callback function as its first argument, and an optional initial value as its second argument. The callback function takes two parameters: an accumulator and the current element being processed. The reduce() method applies the callback function to each element in the array from left to right, and stores the return value of each iteration in the accumulator variable.

Here is an example of using the reduce() method to calculate the sum of an array of numbers:

index.tsx
const numbers = [1, 2, 3, 4, 5];

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

console.log(sum); // Output: 15
168 chars
8 lines

In the example above, the initial value of the accumulator is not provided, so the first iteration uses the first element of the array as the initial value. The callback function takes two parameters, accumulator and currentValue, and returns their sum. The reduce() method applies this callback function to all elements in the array, and returns the final value of the accumulator.

gistlibby LogSnag