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?

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
Jimmy
  • 29
  • 3
  • Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available static and instance methods of [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Sep 17 '21 at 10:53
  • You can search on [LeetCode](https://leetcode.com/problemset/all/) for different challenges / problems / common interview questions and practise them :) – Nakarukatoshi Uzumaki Sep 17 '21 at 10:53
  • 1
    @Jimmy post what you have tried so far – Ramesh Reddy Sep 17 '21 at 10:54
  • Duplicate target found by [Googling “site:stackoverflow.com js merge arrays in object by id”](//google.com/search?q=site%3Astackoverflow.com+js+merge+arrays+in+object+by+id). – Sebastian Simon Sep 17 '21 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] } }), {}))`... – CherryDT Sep 17 '21 at 10:54

1 Answers1

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)
Ramesh Reddy
  • 10,159
  • 3
  • 17
  • 32