Combining arrays from dictionary in Javascript

Viewed 642

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?

6 Answers

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);

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);

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);

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);

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);

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);

Related