Files
30-seconds-of-code/snippets/js/s/sum-array.md
Angelos Chalaris 9d032ce05e Rename js snippets
2023-05-19 20:23:47 +03:00

429 B

title, type, language, tags, cover, dateModified
title type language tags cover dateModified
Array sum snippet javascript
math
secret-tree 2020-10-22T20:24:30+03:00

Calculates the sum of two or more numbers/arrays.

  • Use Array.prototype.reduce() to add each value to an accumulator, initialized with a value of 0.
const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);
sum(1, 2, 3, 4); // 10
sum(...[1, 2, 3, 4]); // 10