I have an array
of objects like this:
[
{"k1":"v1","k2":27172},
{"k1":"v1","k2":15177},
{"k1":"v1","k2":19411},
{"k1":"v2","k2":30163},
{"k1":"v2","k2":23949},
{"k1":"v2","k2":23829},
{"k1":"v2","k2":27821}
]
What's the easiest way to extract the common values from k1 and create a multidimensional array like the below?
[
["v1", [27172, 15177, 19411]],
["v2", [30163, 23949, 23829, 27821]]
];
Here is a solution with some loops.
I created a jsbin here: http://jsbin.com/cucixi/edit?html,js,console
var list = [
{"k1":"v1","k2":27172},
{"k1":"v1","k2":15177},
{"k1":"v1","k2":19411},
{"k1":"v2","k2":30163},
{"k1":"v2","k2":23949},
{"k1":"v2","k2":23829},
{"k1":"v2","k2":27821}
];
var data = {};
list.forEach(function(item){
if (item.k1 in data){
data[item.k1].push(item.k2);
} else {
data[item.k1] = [item.k2];
}
});
var output = [];
for (var key in data){
output.push([key, data[key]]);
}
console.log(output);
Output:
[
["v1", [27172, 27172, 15177, 15177, 19411, 19411]],
["v2", [30163, 30163, 23949, 23949, 23829, 23829, 27821, 27821]]
]
Using reduce
function of array
var test = [
{ "k1": "v1", "k2": 27172 },
{ "k1": "v1", "k2": 15177 },
{ "k1": "v1", "k2": 19411 },
{ "k1": "v2", "k2": 30163 },
{ "k1": "v2", "k2": 23949 },
{ "k1": "v2", "k2": 23829 },
{ "k1": "v2", "k2": 27821 }
]
var out = test.reduce(function(res, obj) {
res[obj.k1] = res[obj.k1] || [];
res[obj.k1].push(obj.k2)
return res;
}, {});
var result = [];
for (var key in out) {
result.push([key, out[key]])
};
console.log(JSON.stringify(result, null, 2))
will give
[
["v1", [27172, 15177, 19411]],
["v2", [30163, 23949, 23829, 27821]]
];
jsfiddle: https://jsfiddle.net/aLnc9oh1/
The solution:
function solution(A)
{
// make an object with an array of values
var temp = {};
for (var i=0, ii=A.length; i<ii; i++)
{
var prop = A[i]['k1'];
if (temp[prop])
temp[prop].push(A[i]['k2']);
else
temp[prop] = [A[i]['k2']];
}
// reformat that into the 2D array like desired
var retArr = [];
for (var key in temp)
retArr.push([key, temp[key]]);
// return it!
return retArr;
}
For the given data returns:
[
["v1", [27172, 15177, 19411]],
["v2", [30163, 23949, 23829, 27821]]
]
You might want to use a combination of Array.prototype.map()
and Object.keys()
var obj = data.reduce((acc, x) => {
acc[x.k1] = (acc[x.k1] || []).concat(x.k2));
return acc;
}, {});
var res = Object.keys(obj).map(x => [x, obj[x]]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.