3

I have the following structure:

ley objects = {
   key1: [1, 2, 3],
   key2: [3,4,6],
   key3: [5, 6, 7],
}

How can I combine those arrays keeping any duplicates so I will have [1, 2, 3, 3, 4, 6, 6, 6, 7]? I have tried concat but I cannot seem to find a way to do so. I have many more keys so it has to be some loop:

My attempt so far:

let arr = []
for(const [key, value] of Object.entries(objects)){ 
    arr.concat(value);
}

Would there be a possible way to avoid this loop?

ashes999
  • 1,234
  • 1
  • 12
  • 36
  • 3
    You mentioned you've "*tried `concat`*" - can you include that attempt here, so that the community might be able to point out where your current approach is flawed? – esqew Mar 25 '21 at 13:09
  • @esqew - my bad, added my attempt – ashes999 Mar 25 '21 at 13:15
  • Why does 6 appear 3 times in your output? What happened to 5? – Nick Parsons Mar 25 '21 at 13:17
  • 2
    `.concat()` produces a new array, so you need to assign it: `arr = arr.concat(value)` – VLAZ Mar 25 '21 at 13:17
  • Related: [Javascript Array Concat not working. Why?](https://stackoverflow.com/q/12803604) and [JavaScript: How to join / combine two arrays to concatenate into one array?](https://stackoverflow.com/q/3975170) – VLAZ Mar 25 '21 at 13:21

6 Answers6

5

You could flat the values from the array.

let object = { key1: [1, 2, 3], key2: [3, 4, 6], key3: [5, 6, 7] },
    result = Object.values(object).flat();

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

You can use ES6 spread syntax.

const obj = {
  key1: [1, 2, 3],
  key2: [3, 4, 6],
};

const result = [...obj.key1, ...obj.key2];
console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42
1

In this scenario, I'd use Array.prototype.flat() in conjunction with Object.values():

const obj = {
  key1: [1, 2, 3],
  key2: [3, 4, 6],
};

const result = Object.values(obj).flat();
console.log(result);
esqew
  • 42,425
  • 27
  • 92
  • 132
1

You can use Array.prototype.concat(),Array.prototype.reduce() and Object.values().

const obj = {
    key1: [1, 2, 3],
    key2: [3, 4, 6],
    key3: [5, 6, 7]
};

const result = Object.values(obj).reduce((acc, item) => acc.concat(item), []);
console.log(result);
0

I assume you aim not only to merge the arrays but also to sort them as per your output. In this case, you can loop through the keys and push them in one array. After that, you can sort them by value.

const obj = {
   key1: [1, 2, 3],
   key2: [3,4,6]
};

const unsorted = Object.keys(obj).reduce((acc, key) => {
  acc.push(...obj[key]);
  return acc;
}, []);

const sorted = [...unsorted].sort((a, b) => a - b);

console.log(sorted);
fyasir
  • 2,924
  • 2
  • 23
  • 36
0

This will also work

    let objects = {
   key1: [1, 2, 3],
   key2: [3,4,6],
   key3: [5, 6, 7],
}
        result = Object.values(objects).join();

console.log(result);
shotgun02
  • 756
  • 4
  • 14