如何跳过在其他条件下找到的值,现在在我的代码中它输出重复项。
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};
}
});
只需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 )
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句