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 resultArray
during the map()
loop. So resultArray.includes(tag)
is always false, so you do return tag
every time.
Use a Set
instead of an array, it automatically removes duplicates.
let resultSet = new Set(allRecipes.map(r => r.tag));
If you want an array, you can convert it at the end:
let resultArray = [...resultSet];
const allRecipes = [{
tag: "Breakfast"
}, {
tag: "Lunch",
}, {
tag: "Dinner",
}, {
tag: "Breakfast"
}];
let resultSet = new Set(allRecipes.map(r => r.tag));
let resultArray = [...resultSet];
console.log(resultArray);