How to Sum Arrays in JavaScript

How to Sum Arrays in JavaScript

Summing arrays in JavaScript involves adding all the elements of an array to get a total. This can be efficiently done using the reduce method. Here’s a comprehensive guide on different ways to sum arrays, including handling multi-dimensional arrays and filtering non-numeric values.

1. Basic Sum Using Reduce

The reduce method applies a function to each element of the array, accumulating a result. To sum an array, initialize the accumulator to 0 and add each element.

Example: Sum a Simple Array

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 15

2. Summing Multi-Dimensional Arrays

For multi-dimensional arrays, first flatten them using the flat method, then apply reduce.

Example: Sum Nested Arrays

const nestedNumbers = [[1, 2], [3, 4], [5, 6]];
const sumNested = nestedNumbers.flat().reduce((acc, curr) => acc + curr, 0);
console.log(sumNested); // Output: 21

3. Handling Non-Numeric Values

Filter out non-numeric values using filter before summing to avoid type errors.

Example: Sum with Non-Numeric Values

const mixedArray = [1, '2', null, 3, undefined, 4];
const sumFiltered = mixedArray
  .filter(item => typeof item === 'number')
  .reduce((acc, curr) => acc + curr, 0);
console.log(sumFiltered); // Output: 8

Edge Cases

  • Empty Array: Returns 0.
  • Single Element: Returns that element.
  • Negative Numbers: Handled correctly by addition.

Why Use Reduce?

  • Concise and readable.
  • Efficiently handles arrays of any size.

Conclusion

Summing arrays in JavaScript can be efficiently achieved using the reduce method. Depending on the array structure and data types, you can combine it with flat and filter for more complex scenarios. This method is both efficient and easy to understand, making it a powerful tool in your JavaScript toolkit.

Index
Scroll to Top