How do I concatenate values into an array by key?
I have data that looks like this:
data = [
[
{"name":"cpumhz","data":[[1433856538,0],[1433856598,0]]},
{"name":"mem","data":[[1433856538,13660],[1433856598,13660]]}
],
[
{"name":"cpumhz","data":[[1433856538,0],[1433856598,0]]},
{"name":"mem","data":[[1433856538,13660],[1433856598,13660]]}
],
[
{"name":"cpumhz","data":[[1433856538,0],[1433856598,0]]},
{"name":"mem","data":[[1433856538,13660],[1433856598,13660]]}
]
];
how to use a map to concatenate array elements so that the attributes data
are concatenated?
Same:
data = [
[
{"name":"cpumhz","data":[[1433856538,0],[1433856598,0],[1433856538,0],[1433856598,0], [1433856538,0],[1433856598,0]]},
{"name":"mem","data":[[1433856538,13660],[1433856598,13660], [1433856538,13660],[1433856598,13660], [1433856538,13660],[1433856598,13660]]}
]
];
I'm getting closer by doing it non-programmatically like this:
res = []
cpudata = _.flatten([data[0][0].data, data[1][0].data, data[2][0].data])
res.push({name: 'cpumhz', data: cpudata})
memdata = _.flatten([data[0][1].data, data[1][1].data, data[2][1].data])
res.push({name: 'mem', data: memdata})
source to share
Have a look at using the reduce function . Underscore / lodash have equivalent functionality.
Essentially you want to take data
and reduce it to 1 array with 2 values. Something like the following should work:
var reducedData = data.reduce(function(prev, cur) {
prev.forEach(function(value, index) {
value.data = value.data.concat(cur[index].data);
});
return prev;
});
You go over each value in data
and decrement it. You concatenate the previous sub-data with the current subjects and return a new value.
source to share
With lodash, you can do something like this:
_(data)
.flatten()
.groupBy('name')
.reduce(function(result, item, key) {
return result.concat([{
name: key,
data: _.flatten(_.pluck(item, 'data'))
}]);
}, []);
You use flatten () to create an array, which can then be grouped into an object based on the value name
using groupBy () . At this point, you have an object with two properties - cpuhz
and mem
.
It is now easy to shrink () the object in the desired array.
source to share