skip to Main Content

I am new to JS and continue learning.
I have an below array object which has duplicate ids in it. I want to iterate and create new array which contains only unique id’s

const testobj = {"100": [295, 681, 15220], "257": [295, 681, 1123]}

So the final output I am looking for
const ids = [295, 681,15220, 1123]

I know this is simple but any help will be appreciated.

2

Answers


  1. const testobj = {"100": [295, 681, 15220], "257": [295, 681, 1123]};
    
    let merged = [].concat(...Object.values(testobj)); 
    const ids = [...new Set(merged)];
    
    console.log(ids);  // [295, 681, 15220, 1123]

    You can achieve this by iterating over the values of the testobj object, merging them, and then creating a Set to filter out duplicates. Finally, you can convert the Set back into an array.

    const testobj = {"100": [295, 681, 15220], "257": [295, 681, 1123]};
    
    let merged = [].concat(...Object.values(testobj)); 
    const ids = [...new Set(merged)];
    
    console.log(ids);  // [295, 681, 15220, 1123]
    
    Login or Signup to reply.
  2. You can try using Set.

    First extract all the arrays of IDs using Object.values(), then flatten these arrays into a single array using [].concat(). Next Set is used to remove the duplicate IDs. Finally [...] (using spread syntax (…)) is used to convert the Set back into an array.

    const testobj = {"100": [295, 681, 15220], "257": [295, 681, 1123]};
    const uniqueIds = [...new Set([].concat(...Object.values(testobj)))];
    console.log(uniqueIds);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search