I have an array of objects structured like this:
data: [
a:[
{keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15},
{keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15},
{keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15},
{keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15}
]
]
The task is to identify all keys with numeric values, sum them up, and create a new object with the key and its corresponding sum.
The expected result should be:
sums = { keythree: 92, keyfour: 60 }
I am currently using Lodash
library for this. Here is my existing code:
//Get all group names
var keys = Object.keys(data);
//Iterate through each group
for(var i = 0; i< keys.length; i++) {
//For each user record in the group
_u.forEach(data[keys[i]], function(item) {
//Identify keys with numeric values
var numKeys = Object.keys(_u.pick(item, _u.isNumber));
//Calculate sum for each numeric key
_u(numKeys).forEach(function(n) {
_u.set(sums, n+'['+keys[i]+']', _u.sum(_u.map(data[keys[i]], n)));
}).value();
});
}
The current implementation works as intended, but I am looking to optimize it by reducing loops for better efficiency. I believe Lodash
might offer a more efficient solution, although navigating the documentation can be challenging.