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()
You're not updating
resultArrayduring themap()loop. SoresultArray.includes(tag)is always false, so you doreturn tagevery time.Use a
Setinstead of an array, it automatically removes duplicates.If you want an array, you can convert it at the end: