How to sum value in javascript array object form specific search id?

General Tech Bugs & Fixes 2 years ago

0 4 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (4)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

I have javascript array object as below. My need is to sum value base on seach id in the array object.

 

var array = [
{ id: 1, val: 10 }, 
{ id: 2, val: 25 }, 
{ id: 3, val: 20 }, 
{ id: 1, val: 30 }, 
{ id: 1, val: 25 }, 
{ id: 2, val: 10 }, 
{ id: 1, val: 20 }
],

For example sum of value for id 1 is 10 + 30 + 25 + 20 = 85 , It may be something link linq but I'm not sure in javascript.

 

profilepic.png
manpreet 2 years ago

You can use a combination of filter and reduce to get the result you want:

sumOfId = (id) => array.filter(i => i.id === id).reduce((a, b) => a + b.val, 0);

Usage:

const sumOfb.com/tag/1">1 = sumOfId(b.com/tag/1">1); //b.com/tag/85">85

 

0 views   0 shares

profilepic.png
manpreet 2 years ago

A way to do it with a traditional for loop

var array = [
  { id: 1, val: 10 }, 
  { id: 2, val: 25 }, 
  { id: 3, val: 20 }, 
  { id: 1, val: 30 }, 
  { id: 1, val: 25 }, 
  { id: 2, val: 10 }, 
  { id: 1, val: 20 }
];

var sums = {};
for (var i = 0; i < array.length; i++) {
  var obj = array[i];
  sums[obj.id] = sums[obj.id] === undefined ? 0 : sums[obj.id];
  sums[obj.id] += parseInt(obj.val);
}

console.log(sums);

0 views   0 shares

profilepic.png
manpreet 2 years ago
var array = [
{ id: 1, val: 10 }, 
{ id: 2, val: 25 }, 
{ id: 3, val: 20 }, 
{ id: 1, val: 30 }, 
{ id: 1, val: 25 }, 
{ id: 2, val: 10 }, 
{ id: 1, val: 20 }
];

function getSum(arr, id){
  return arr.reduce((a,c) => {
    if(c.id == id) a += c.val;
    return a; 
  }, 0);
}

console.log(getSum(array, 1)); //85
console.log(getSum(array, 2)); //35
console.log(getSum(array, 3)); //20

0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.