Reputation: 448
I have a data object
data : [
["1", 20],
["1", 24],
["1", 2],
["1", 32],
["1", 23],
["1", 80],
["2", 3],
["2", 32],
["2", 34],
["2", 36],
["2", 36]]
Now I want the object to be grouped like this ie "1" grouped in one array and same for the "2"
"data" : [
["1", [20, 24, 2, 32, 23, 80]],
["2", [3, 32, 34, 36, 36]]
]
Upvotes: 1
Views: 45
Reputation: 2519
I don't know what are you trying to achieve, but that's one way you can structure such an array:
var ones = ["1",[]];
var twos = ["2",[]];
var data2 = [];
function go() {
for(var i = 0; i < data.length; i++) {
minidata = data[i];
if(minidata[0] === "1") {
ones[1].push(minidata[1]);
} else if ( minidata[0] === "2") {
twos[1].push(minidata[1]);
}
}
data2.push(ones);
data2.push(twos);
console.log(data2);
}
Check the console to see the results.
Upvotes: 0
Reputation: 192477
Try this (fiddle - look at the console):
var obj = {
data : [
["1", 20],
["1", 24],
["1", 2],
["1", 32],
["1", 23],
["1", 80],
["2", 3],
["2", 32],
["2", 34],
["2", 36],
["2", 36]]
};
function group(data) {
var mapObj = data.reduce(function (map, item) { // create a map of the key: [values]
var key = item[0];
var value = item[1];
map[key] && map[key].push(value) || (map[key] = [value]);
return map;
}, {});
return Object.keys(mapObj).map(function (key) { // map the keys and values back to arrays
return [key, mapObj[key]];
});
}
var newObj = {
data: group(obj.data)
};
Upvotes: 2