Categories

See More
Popular Forum

MBA (4887) B.Tech (1769) Engineering (1486) Class 12 (1030) Study Abroad (1004) Computer Science and Engineering (988) Business Management Studies (865) BBA (846) Diploma (746) CAT (651) B.Com (648) B.Sc (643) JEE Mains (618) Mechanical Engineering (574) Exam (525) India (462) Career (452) All Time Q&A (439) Mass Communication (427) BCA (417) Science (384) Computers & IT (Non-Engg) (383) Medicine & Health Sciences (381) Hotel Management (373) Civil Engineering (353) MCA (349) Tuteehub Top Questions (348) Distance (340) Colleges in India (334)
See More

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

General Tech Bugs & Fixes

Max. 2000 characters
Replies

usr_profile.png

User

( 7 months 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.

 

usr_profile.png

User

( 7 months 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 sumOf1 = sumOfId(1); //85

 

usr_profile.png

User

( 7 months 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);

usr_profile.png

User

( 7 months 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

what's your interest


forum_ban8_5d8c5fd7cf6f7.gif