gwydion93
gwydion93

Reputation: 1923

Combining nested arrays into a single array with unique items

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?

Upvotes: 2

Views: 812

Answers (2)

Mohit Agrawal
Mohit Agrawal

Reputation: 1

var arr=[];

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

Upvotes: -1

Spectric
Spectric

Reputation: 31987

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

Upvotes: 5

Related Questions