2

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?

4
  • 2
    const newArray = Array.from(new Set(hex_ids.flatMap(item => item))) Commented Aug 3, 2021 at 14:09
  • 1
    @secan - No reason to use flatMap, we have flat, avoiding the callback. Commented Aug 3, 2021 at 14:13
  • ... actualy using flatMap() is pointless when a simple flat() would do, as you can see in the answer from @Spectric Commented Aug 3, 2021 at 14:13
  • 1
    @T.J.Crowder, yep, I realized it when I saw the answer from Spectric but thanks anyway :) Commented Aug 3, 2021 at 14:15

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that worked great! Literally the simplest and cleanest solution and I can't believe I've never seen .flat before.
-1
var arr=[];

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

1 Comment

Welcome to StackOverflow! Please take some time to elaborate on your answer and tell the OP and future readers, why, your particular solution works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.