10 examples of 'javascript sum array of objects by key' in JavaScript

Every line of 'javascript sum array of objects by key' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
5function sumByKey(items, key) {
6 const sum = items.reduce((prevSum, item) => prevSum + item[key], 0);
7 return sum;
8}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

1283function arrayToObjectsById(array, keyOf) {
1284 return array.reduce(function (objectsById, item) {
1285 objectsById[keyOf(item)] = item;
1286 return objectsById;
1287 }, {});
1288}
24function sumCountObjects(obj1, obj2) {
25 return Object.keys(obj2).reduce((summaryObj, key) => {
26 if (summaryObj[key] == null) {
27 summaryObj[key] = obj2[key];
28 } else {
29 summaryObj[key] += obj2[key];
30 }
31 return summaryObj;
32 }, Object.assign({}, obj1));
33}
66function sum(array){
67 var s = 0;
68 for(var i = 0; i < array.length; i++){
69 s += array[i];
70 }
71 return s;
72}
45function iterativeSum(array) {
46 let total = 0;
47 array.forEach(function (n) {
48 total += n;
49 });
50 return total;
51}
2function sum(...nums) {
3 if (nums.length === 1 && Array.isArray(nums[0])) {
4 nums = [...nums[0]];
5 }
6 return nums.reduce((a, b) => a + b);
7}
116function mySumFunction(array, sum) {
117 console.log(array.reduce(sum));
118 console.log('-----------------------');
119}
37function arraySum(array) {
38 return array.reduce(
39 (sum, curr) =>
40 sum + (curr ? 1 : 0) // if curr is 0 (no edge) or undefined (loop not allowed), sum remains unchanged
41 , 0,
42 );
43}
25function Sum(array) {
26 // Computes array[0] + array[1] + ... + array[n-1]
27 var tsum = 0;
28 for(var i = 0, l = array.length;i <l ;i+=1) {
29 tsum += array[i];
30 }
31 return tsum;
32}
494export function arraySum (array: NumberArray, stride = 1, offset = 0) {
495 const n = array.length
496 let sum = 0
497 for (let i = offset; i < n; i += stride) {
498 sum += array[ i ]
499 }
500 return sum
501}

Related snippets