This is a question that I have encountered during an interview:
Write a function to transform the array:
[
{name:'a',values:[1,2]},
{name:'b',values:[3]},
{name:'a',values:[4,5]}
]
to:
[
{name:'a',values:[1,2,4,5]},
{name:'b',values:[3]}
]
I know this is not hard, but I just can't figure it out. Does anyone know how to solve it? Are there any places that I can find and practice more practical questions like this one?
You can group the array by name and then get an array using the grouped object:
const bla = [
{name:'a',values:[1,2]},
{name:'b',values:[3]},
{name:'a',values:[4,5]}
];
const res = Object.values(bla.reduce((obj, { name, values }) => {
obj[name] = obj[name] ?? {name, values: []}
obj[name].values.push(...values)
return obj
}, {}));
console.log(res)