0

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?

5
  • Familiarize yourself with how to access and process nested objects, arrays or JSON and how to create objects and use the available static and instance methods of Object and Array. Commented Sep 17, 2021 at 10:53
  • You can search on LeetCode for different challenges / problems / common interview questions and practise them :) Commented Sep 17, 2021 at 10:53
  • 1
    @Jimmy post what you have tried so far Commented Sep 17, 2021 at 10:54
  • Duplicate target found by Googling “site:stackoverflow.com js merge arrays in object by id”. Commented Sep 17, 2021 at 10:54
  • If you want to write the code functional, a few ideas: [...new Set(arr.map(x => x.name))].map(name => ({ name, values: arr.filter(x => x.name === name).map(x => x.values).flat() })) or Object.values(arr.reduce((a, { name, values }) => ({ ...a, [name]: { name, values: [...a[name]?.values ?? [], ...values] } }), {}))... Commented Sep 17, 2021 at 10:54

1 Answer 1

0

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.