yandex
loader

please wait

  • Jadav Payeng Mar-07-2019 08:54:48 AM ( 2 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.

     

  • Jignesh Patel Mar-07-2019 08:56:50 AM ( 2 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

     
  • Vanshika Bhatt Mar-07-2019 08:58:46 AM ( 2 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);
  • Pooja Bhardwaj Mar-07-2019 09:10:39 AM ( 2 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

Please login

Similar Discussion

Recommended For You