数组存储重复的元素,即使排除了它们

Array stores duplicate elements even after excluding them

提问人:IHateCoding 提问时间:10/15/2023 最后编辑:BergiIHateCoding 更新时间:10/20/2023 访问量:69

问:

我尝试将元素动态添加到数组中。如果 Array 中的元素存在,则跳过它,如果不存在,则添加它。.map() 函数中的控制台.log显示,已添加值。但是,它增加了太多。

食谱.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)
}

控制台.log

[ Breakfast, Lunch, Lunch, Breakfast ]

我做错了什么?Includes 不起作用,new Set() 也不起作用

javascript html 节点.js 数组 array.prototype.map

评论

1赞 Bergi 10/15/2023
请不要用解决方案更新您的问题,不再清楚为什么它不起作用,问题的答案将失效。如果你想展示自己的解决方案,你可以自己写一个答案

答:

1赞 Barmar 10/15/2023 #1

在循环期间,您没有更新。所以总是假的,所以你每次都这样做。resultArraymap()resultArray.includes(tag)return tag

使用 a 代替数组,它会自动删除重复项。Set

let resultSet = new Set(allRecipes.map(r => r.tag));

如果你想要一个数组,你可以在最后转换它:

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);

评论

0赞 IHateCoding 10/15/2023
非常感谢巴马尔。当我从字面上复制并粘贴您的解决方案以替换我的错误代码时,它会导致相同的结果......let resultArray = new Set(allRecipes.map( recipe => recipe.tag)) 是 recipes 中的代码.js [ Breakfast, Lunch, Lunch, Breakfast ] 是控制台.log
0赞 Barmar 10/15/2023
我添加了一个可运行的片段,表明它有效。
0赞 Barmar 10/15/2023
检查空格中的差异。用于从字符串中删除周围的 whitespce。trim()
0赞 Shaheer Khan 10/15/2023 #2

对于简单数组,您可以使用

const uniqueArray=[...new Set(array)];

for 对象数组

const uniqueArray = array.filter((item, index) => {
     return index === array.findIndex(obj => obj['key'] === item['key'])
});

console.log(uniqueArray);
<script>
const array  = [{
  key: "Breakfast"
}, {
  key: "Lunch",
}, {
  key: "Dinner",
}, {
  key: "Breakfast"
}];
</script>

评论

0赞 Alexander Nenashev 10/15/2023
不起作用....
0赞 Shaheer Khan 10/20/2023
@AlexanderNenashev解决方案确实有效,但问题是插入的代码片段,对象的键中存在不匹配/拼写错误。已经修好了
1赞 Alexander Nenashev 10/15/2023 #3

您可以在检查集合中的重复项时减少数组:

const result = allRecipes.reduce((r, {tag}) => (r.set.has(tag) || (r.set.add(tag), r.arr.push(tag)), r), {set: new Set, arr:[]}).arr;

console.log(result);
<script>
const allRecipes = [{
  tag: "Breakfast"
}, {
  tag: "Lunch",
}, {
  tag: "Dinner",
}, {
  tag: "Breakfast"
}];
</script>

它比映射到集合并转换回数组更快,项目越多越快:

` Chrome/118
--------------------------------------------------------
Alexander   1.00x  |  x10000000  873  891  902  905  905
Barmar      1.41x  |   x1000000  123  125  127  134  139
--------------------------------------------------------
https://github.com/silentmantra/benchmark `

const allRecipes = [
{
  tag: "Breakfast"
}, {
  tag: "Lunch",
}, {
  tag: "Dinner",
}, {
  tag: "Breakfast"
},
{
  tag: "Breakfast"
}, {
  tag: "Lunch",
}, {
  tag: "Dinner",
}, {
  tag: "Breakfast"
},
{
  tag: "Breakfast"
}, {
  tag: "Lunch",
}, {
  tag: "Dinner",
}, {
  tag: "Breakfast"
},
{
  tag: "Breakfast"
}, {
  tag: "Lunch",
}, {
  tag: "Dinner",
}, {
  tag: "Breakfast"
},
];

// @benchmark Barmar
[...new Set(allRecipes.map(r => r.tag))];


// @benchmark Alexander

allRecipes.reduce((r, {tag}) => (r.set.has(tag) || (r.set.add(tag), r.arr.push(tag)), r), {set: new Set, arr:[]}).arr;

/*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0='));