Last active
May 30, 2020 15:40
-
-
Save jherax/a9846d44b62b64d7a182d6d6ec9de526 to your computer and use it in GitHub Desktop.
Sums all the values in an array by reducing it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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