[英]Find common elements in 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 有一個數組類型的內置方法:
.filter( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter )
和
.some ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some )
當您讀出 function 時,它會說“過濾所有數組(全部),如果current
元素的some
text
等於all
元素中的該元素,則將其刪除( !
)”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.