在Array中查找常见元素



我有一个所有公司对象的数组

const all= [{'text': 'first'}, {'text':'second'},{'text:': 'third'}]

以及目前公司的一系列

const current = [{'text:': 'third'}]

帮助只留下那些";文本";中未复制的元素调用"的数组;所有";

我试图找到解决方案,但我错过了的经验

const all= [{'text': 'first'}, {'text':'second'},{'text:': 'third'}]
const current = [{'text:': 'third'}]
function test(){
const result =  all.filter(el=>{
if(all.some(element=> el.text === element.text)){
return false
} else {
return true
}
})

console.log(result)
}
test()

重要的是,搜索应该通过文本命名,因为id可能与不同

const all= [{'text': 'first'}, {'text':'second'},{'text:': 'third'}];
const current = [{'text:': 'third'}];
all.filter(ele => !current.some(cur => cur.text === ele.text))
// output
// [{text: "first"}, {text: "second"}]

有很多方法可以解决这个问题。您可以使用简单的for循环,但JS在数组类型上有内置方法:

.过滤器(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)

.一些(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)

当你读出函数时,它会说";过滤所有数组(all(,如果current元素的textsome等于all中的那个元素,则移除它(!(";

最新更新