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
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.
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.