I am a JavaScript beginner. I want to merge a nested array with "id" <-- unique for all the array of objects. The dummy is just a data that is extra and should come outside with id
let arr1 = [
{
A: 0.71,
B: 0.52,
id: 1,
dummy: 1,
},
{
A: 0.72,
B: 0.50,
id: 2,
dummy: 1,
},
];
let arr2 = [
{
A: 0.157,
B: 0.02255,
id: 1,
dummy: 1,
},
{
A: 0.16761,
B: 0.028281,
id: 2,
dummy: 1,
},
];
let arr3 = [
{
A: 0.55,
B: 0.50,
id: 1,
dummy: 1,
},
{
A: 0.5,
B: 0.43,
id: 2,
dummy: 1,
},
];
I want these in one array as finalArray with contains id and all the three arrays inside those with their respective ids
let finalArr = [
{
id: 1,
dummy: 1,
arr1: { A: 0.71, B: 0.52 },
arr2: { A: 0.157, B: 0.02255 },
arr3: { A: 0.55, B: 0.50 }
},
{
id: 2,
dummy: 1,
arr1: { A: 0.72, B: 0.50 },
arr2: { A: 0.16761, B: 0.028281 },
arr3: { A: 0.5, B: 0.43 }
},
]
CodePudding user response:
You can first gather the data by id using a .reduce()
, then transform the data into your desired array format:
let arr1 = [
{ A: 0.71, B: 0.52, id: 1, dummy: 1, },
{ A: 0.72, B: 0.50, id: 2, dummy: 1, },
];
let arr2 = [
{ A: 0.157, B: 0.02255, id: 1, dummy: 1, },
{ A: 0.16761, B: 0.028281, id: 2, dummy: 1, },
];
let arr3 = [
{ A: 0.55, B: 0.50, id: 1, dummy: 1, },
{ A: 0.5, B: 0.43, id: 2, dummy: 1, },
];
let idMap = arr1.concat(arr2).concat(arr3).reduce((acc, obj) => {
if(!acc[obj.id]) {
acc[obj.id] = {
dummy: obj.dummy,
arrs: []
}
}
acc[obj.id].arrs.push({ A: obj.A, B: obj.B });
return acc;
}, {});
let finalArr = Object.keys(idMap).map(id => {
let obj = {
id: id,
dummy: idMap[id].dummy
};
let idx = 1;
idMap[id].arrs.forEach(o => {
obj['arr' idx ] = o;
});
return obj;
});
console.log(finalArr);
CodePudding user response:
The same solution without map and reduce methods for old browsers as well
let arr1 = [
{ A: 0.71, B: 0.52, id: 1, dummy: 1, },
{ A: 0.72, B: 0.50, id: 2, dummy: 1, },
];
let arr2 = [
{ A: 0.157, B: 0.02255, id: 1, dummy: 1, },
{ A: 0.16761, B: 0.028281, id: 2, dummy: 1, },
];
let arr3 = [
{ A: 0.55, B: 0.50, id: 1, dummy: 1, },
{ A: 0.5, B: 0.43, id: 2, dummy: 1, },
];
let finalArr = []
let keysToUse = ['id', 'dummy'];
let countOfIds = arr1.length;
let ids = arr1.map(d => d.id);
let varArrayToUse = ['arr1', 'arr2', 'arr3'];
// console.log('len ' countOfIds)
for(var i = 0; i < ids.length; i ){
finalArr[i] = {
id: arr1[i].id,
dummy: arr1[i].dummy,
}
for(var j = 0; j < varArrayToUse.length; j ) {
if (j == 0) { targetArr = arr1 } else if (j == 1) {targetArr = arr2} else {targetArr = arr3}
finalArr[i][varArrayToUse[j]] =
{
A: (targetArr[i]).A,
B: (targetArr[i]).B
}
}
}
console.log(finalArr)