Search code examples
javascriptarraysjsonloopsobject

Loop through array of objects, sum array elements and put result in last element


I have an array of objects as follows. Each object has an array P2 inside it.

let input = [ 
     { "P2": [ 6, 6, 0 ] },
     { "P2": [ 3, 2, 0 ] },
     { "P2": [ 5, 1, 0 ] },
]

I want the desired result. as you can see, i am adding the elements and putting the result in the last element. for e.g. adding 6+6+0 and putting the result in last element as 12. Similarly for other objects inside the array. So the final output will look like this.

   [ 
     { "P2": [ 6, 6, 0, 12 ] },
     { "P2": [ 3, 2, 0, 5 ] },
     { "P2": [ 5, 1, 0, 6 ] },
   ]

I am able to achieve this with a simple loop and reduce function as shown below.

input.forEach(arrayItem => {
  let sum = arrayItem.P2.reduce((partialSum, a) => partialSum + a, 0);
  arrayItem.P2.push(sum)
});

console.log(input)

Its fine till here. but it gets really interesting when i have dynamic input. for e.g. inside for static P2 values, i can have anything else. For e.g. shown below are the 2 examples of dynamic input.

let input = [ 
     { "P1": [ 6, 6, 0 ] },
     { "P2": [ 3, 2, 0 ] },
     { "P3": [ 5, 1, 0 ] },
]

OR

let input = [ 
     { "P2": [ 3, 3, 3, 2 ] },
     { "P2": [ 7, 7, 7, 4 ] },
     { "Total": [ 5, 1, 4, 6 ] },
]

Can someone let me know how to modify my code if there is dynamic property names like this.


Solution

  • you can iterate over each object in the array and dynamically access the property name using Object.keys() or Object.entries().

    let input = [ 
        { "P1": [ 6, 6, 0 ] },
        { "P2": [ 3, 2, 0 ] },
        { "P3": [ 5, 1, 0 ] },
    ];
    
    input.forEach(arrayItem => {
        let propertyName = Object.keys(arrayItem)[0];
        let values = arrayItem[propertyName];
        let sum = values.reduce((partialSum, value) => partialSum + value, 0);
        values.push(sum);
    });
    
    console.log(input);

    Using your second example

    let input = [ 
         { "P2": [ 3, 3, 3, 2 ] },
         { "P2": [ 7, 7, 7, 4 ] },
         { "Total": [ 5, 1, 4, 6 ] },
    ]
    
    input.forEach(arrayItem => {
        let propertyName = Object.keys(arrayItem)[0];
        let values = arrayItem[propertyName];
        let sum = values.reduce((partialSum, value) => partialSum + value, 0);
        values.push(sum);
    });
    
    console.log(input);