1

I loop through an array for fetching the dynamic content. But, I couldn't remove the duplicate values while doing the foreach looping since every array element is taken into account inforEach (I can't change to for loop). Is there any solution for removing the duplicate values? I even tried creating the array after each iteration with different method. But, I was only getting the last iteration value.

forEach(( filteredItems ) => {
 filteredItems.languageCodes.forEach(( languageCode ) => {
 finalLanguage=languageCode;
arrayCreation(finalLanguage);             
                    })
                })

 function arrayCreation(finalLanguage){
                     langArray=[];
                    langArray.push(finalLanguage);
                    console.log("langArray", langArray);
                }

This is my filteredItems and filteredItems.languageCodes

Thanks!

aadhira
  • 321
  • 1
  • 3
  • 16

2 Answers2

2

You could use a Set to remove duplicates instead. Something like this should work:

let set = new Set(array);
array = Array.from(set);

EDIT

To answer the question in the title (for those users who get here based on that), one approach to storing the values after each iteration uses the reduce method of Arrays.

reduce takes an accumulator, which could be something like an Array or Set (however, map is probably a better approach than using an Array as the accumulator).

scottysseus
  • 1,922
  • 3
  • 25
  • 50
0

You can remove duplicates in an Array using Lodash.

Have a look on this: uniqBy

Premshankar Tiwari
  • 3,006
  • 3
  • 24
  • 30