For the following array :
JavaScript
x
18
18
1
const a = [
2
{
3
26: [0],
4
27: [100],
5
28: [0]
6
},
7
{
8
26: [0],
9
27: [100],
10
28: [0]
11
},
12
{
13
26: [0],
14
27: [100],
15
28: [0]
16
}
17
]
18
I need a function that should merge arrays with the same keys in the object.
JavaScript
1
6
1
`const result = [{
2
26: [0,0,0],
3
27: [100,100,100],
4
28: [0,0,0]
5
}]`
6
Advertisement
Answer
Try to use reduce
JavaScript
1
20
20
1
const data = [{
2
26: [0], 27: [100], 28: [0]
3
},
4
{
5
26: [0], 27: [100], 28: [0]
6
},
7
{
8
26: [0], 27: [100], 28: [0]
9
}
10
];
11
12
const restructure = arr =>
13
[arr.reduce((accumu, current) => {
14
for (const [key, val] of Object.entries(current)) {
15
accumu[key] = [accumu[key] ?? '', val];
16
}
17
return accumu;
18
}, {})];
19
20
console.log(JSON.stringify(restructure(data)));