I try to dynamically add elements to an Array. If the element in the Array exists, skip it, if it does not exist, add it. The console.log within the .map() function shows, that values have been added. However, it adds too many.
recipes.js
const getUniqueTags = async (req,res)=>{
const allRecipes = await Recipe.find({}).select("tag");
let resultArray =[];
resultArray = allRecipes.map( recipe =>{
const tag = recipe.tag;
if(resultArray.includes(tag)){
}
else{
return tag;
}
});
console.log(resultArray);
res.status(200).json(resultArray)
}
console.log
[ Breakfast, Lunch, Lunch, Breakfast ]
What am I doing wrong? Includes does not work, neither does new Set()
2
Answers
You’re not updating
resultArray
during themap()
loop. SoresultArray.includes(tag)
is always false, so you doreturn tag
every time.Use a
Set
instead of an array, it automatically removes duplicates.If you want an array, you can convert it at the end:
For Simple array you can use
const uniqueArray=[...new Set(array)];
for Array of objects