How to use javascript to loop through key, values and add one key value when another match
I have a dataset of records that looks like this:
[{
"d1d":"2015-05-28T00:00:00.000Z",
"d1h":0,
"d15m":0,
"ct":3
},
{
"d1d":"2015-05-28T00:00:00.000Z",
"d1h":0,
"d15m":0,
"ct":1
}
]
The ct value changes with every record. If d1d, d1h and d15m are the same in one or more records, then I need to merge those records into one with the sum of all ct values.
I have jquery, can I use grep for this?
I understand that the server side can improve my data handling, but I have no control over that.
source to share
You don't need to use jQuery for this, vanilla JavaScript will do. I will show you two solutions to your problem:
Example 1: Violating Array # reduce as an iterator
var intermediaryArray = [];
dataset.reduce(function(prev, curr) {
if(prev.d1d === curr.d1d && prev.d1h === curr.d1h && prev.d15m === curr.d15m) {
intermediaryArray.push({
d1d: prev.d1d,
d1h: prev.d1h,
d15m: prev.d15m,
ct: prev.ct + curr.ct
});
} else {
// push the one that wasn't the same
intermediaryArray.push(curr);
}
// return current element so reduce has something to work on
// for the next iteration.
return curr;
});
Example 2: Using Array # Map and Array # Shorten Together
This example uses underscore.js to demonstrate the logic of what you want to do.
.map()
creates a new array of grouped objects.
.groupBy()
creates an array of subarrays containing objects that pass a predicate that all objects must have the same function d1d
or grouping.
.reduce()
boils all subarrays down to one value, your object being appended to ct
each other.
var merged = _.map(_.groupBy(a, 'd1d'), function(subGroup) {
return subGroup.reduce(function(prev, curr) {
return {
d1d: prev.d1d,
d1h: prev.d1h,
d15m: prev.d15m,
ct: prev.ct + curr.ct
};
});
});
source to share
Here's one possible solution:
var dataset = [{
"d1d":"2015-05-28T00:00:00.000Z",
"d1h":0,
"d15m":0,
"ct":3
},
{
"d1d":"2015-05-28T00:00:00.000Z",
"d1h":0,
"d15m":0,
"ct":1
}
]
function addCt(dataset) {
var ctMap = {}
var d1d, d1h, d15m, ct, key, value
for (var ii=0, record; record=dataset[ii]; ii++) {
key = record.d1d+"|"+record.d1h+"|"+record.d15m
value = ctMap[key]
if (!value) {
value = 0
}
value += record.ct
ctMap[key] = value
}
return ctMap
}
ctMap = addCt(dataset)
console.log(ctMap)
// { "2015-05-28T00:00:00.000Z|0|0": 4 }
You might want to build the key in a different way. You can set a value for an object containing d1d, d1h, d15m and cumulated ct values, with one object for all corresponding d1d, d1h, and d15m values.
source to share