Combining nested arrays into a single array with unique items

Viewed 443

Suppose I have an object like this:

 hex_ids = [
    ["8d267451c3858ff", "8d267451c385bbf", "8d267451c385b3f", "8d267451c385b7f", "8d267451c3ae6bf", "8d267451c3ae6ff", "8d267451c3ae67f", "8d267451c3aa93f"], 
    ["8d267451c3aa93f", "8d267451c3ae2ff", "8d267451c3ae27f", "8d267451c3a8cbf", "8d267451c3a8dbf", "8d267451c3a8d3f", "8d267451c3ac6ff"]
 ]

The array has 2 nested array, each with a different length. At least one item in each nested array also exists in the other. What I want to do is combine these 2 nested arrays into a single array with unique items and eliminate any redundancies like this:

hex_ids = ["8d267451c3858ff", "8d267451c385bbf", "8d267451c385b3f", "8d267451c385b7f",
"8d267451c3ae6bf", "8d267451c3ae6ff", "8d267451c3ae67f", "8d267451c3aa93f", "8d267451c3ae2ff", 
"8d267451c3ae27f", "8d267451c3a8cbf", "8d267451c3a8dbf", "8d267451c3a8d3f", "8d267451c3ac6ff"]

What is the easiest method to do this?

2 Answers

Flatten the array with Array#flat and get the unique values:

const array = [
    ["8d267451c3858ff", "8d267451c385bbf", "8d267451c385b3f", "8d267451c385b7f", "8d267451c3ae6bf", "8d267451c3ae6ff", "8d267451c3ae67f", "8d267451c3aa93f"], 
    ["8d267451c3aa93f", "8d267451c3ae2ff", "8d267451c3ae27f", "8d267451c3a8cbf", "8d267451c3a8dbf", "8d267451c3a8d3f", "8d267451c3ac6ff"]
 ]
const result = [...new Set(array.flat())];
console.log(result);

var arr=[];

for(let i of hex_ids){
 arr=arr.concat(i)
}
console.log(Array.from(new Set(arr)))
Related