如何跳过找到的值

rqenqsqc  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(165)

如何跳过else条件下找到的值,现在在我的代码中它会输出重复的值。

this.comparedGenesList = this.genesList.map((item) => {
      const foundedItem = this.data.probes.find(({name}) => name.toUpperCase() === item.toUpperCase());
        if (foundedItem !== undefined) {
         return {name: foundedItem.name.trim(), matched: true, id: foundedItem.id};
        } else {
          return {name: item.trim(), matched: false, id: undefined};
        }
    });
hsgswve4

hsgswve41#

只要钉上钉子就行了 array.filter 在末尾删除所有重复项。

.filter((item, index, array) =>  
  index === array.findIndex((t) => (
    t.name === item.name && t.id === item.id
  ))
)

基本上是说
对于数组中的每个项,执行测试以查看是否需要将其过滤掉。测试是:找到第一个与我们正在测试的对象具有相同名称和id的匹配对象。如果找到的对象的索引与我们正在测试的对象的索引相同,请让它通过。如果它是一个不同的索引(如中所示,我们后来发现了一个副本),则丢弃它。
以下是一个可测试的代码片段:

this.genesList = ['fred','john','dave','john','dave']
this.data = {probes:[{name:'john', id:2}]}

this.comparedGenesList = this.genesList.map((item) => {
  const foundedItem = this.data.probes.find(({name}) => name.toUpperCase() === item.toUpperCase());
  if (foundedItem !== undefined) {
    return {
      name: foundedItem.name.trim(),
      matched: true,
      id: foundedItem.id
    };
  } else {
    return {
      name: item.trim(),
      matched: false,
      id: undefined
    };
  }
}).filter((item, index, array) =>
  index === array.findIndex((t) => (
    t.name === item.name && t.id === item.id
  ))
)

console.log(this.comparedGenesList )
qqrboqgw

qqrboqgw2#

您可以使用filter()而不是map()。

this.comparedGenesList = this.genesList.filter((item) => {
  const isItemFounded = this.data.probes.some((name) => name.toUpperCase() === item.toUpperCase());
  return !isItemFounded;
})
.map((item) => {
      return {name: item.name.trim(), matched: true, id: item.id};
});

相关问题