Skip to content

Instantly share code, notes, and snippets.

@jherax
Last active May 30, 2020 15:40
Show Gist options
  • Save jherax/a9846d44b62b64d7a182d6d6ec9de526 to your computer and use it in GitHub Desktop.
Save jherax/a9846d44b62b64d7a182d6d6ec9de526 to your computer and use it in GitHub Desktop.
Sums all the values in an array by reducing it
/**
* Sums all the values in an array by reducing it.
*
* @param {Array} array: the collection to iterate
* @param {String | Number} prop: (optional) property name or array index
* @return {Number}
*/
function sumValues(array, prop) {
if (!array || !array.length) return 0;
if ((/string|number/).test(typeof prop)) {
return array.reduce((total, cv) => total + (+cv[prop]), 0);
}
return array.reduce((total, cv) => total + (+cv), 0);
}
// reduces an array of numbers and sums all its values
var list = [1, 2, 3, 4, 5];
sumValues(list); // => 15
// reduces an array of string-numbers and sums all its values
list = ['1', '2', '3', '4', '5'];
sumValues(list); // => 15
// sums all values in the property "quantity"
list = [
{id:12345, type:"a", quantity:10},
{id:13458, type:"b", quantity:15},
{id:12765, type:"x", quantity:12},
];
sumValues(list, "quantity"); // => 37
//sums all values at the index 2
list = [
[12345, "tomb-raider", 4],
[12346, "serious-sam", 1],
[12765, "half-life", 3],
[12766, "deus-ex", 2],
];
sumValues(list, 2); // => 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment