2017-03-06 129 views
0

我正在使用React,但概念是在JavaScript中。所以希望我可以爲簡單起見留下React代碼。比較兩個數組中的對象並根據javascript中的匹配返回

我有兩個數組,我需要過濾掉。我的目標是映射數組並檢查該對象的屬性是否與另一個數組的對象中的屬性相匹配。

第一陣列看起來像這樣:

[{id: 1}, {id: 2}, {id: 3}, {id: 4}] 

其次一個看起來像這樣:

[{id: 3}, {id: 4}] 

因此,如果一個對象具有相同的id屬性作爲其他陣列中的一個對象,返回反應元/什麼。

這是我得到的工作,但它只是通過索引並比較它們。這似乎正確地循環第一個數組,但我似乎無法循環索引以外的任何其他數組。

return arr1.map((e, i) => { 
    return if (e.id === arr2[i].id) { 
    return <div>Match</div> 
    } else { 
    return <div>No Match</div> 
    } 
}) 
+0

什麼似乎沒有工作? –

回答

1

你的問題是你要比較索引的索引。你想知道arr1中的元素是,在arr2中的任何地方,對吧?

我會用arr2.filter來搜索所有的arr2。所以,你會是這樣的:

return arr1.map((e1, i) => { 
    if (arr2.filter(e2 => e2.id === e1.id).length > 0) { // If there's a match 
    return <div>Match</div> 
    } else { 
    return <div>No Match</div> 
    } 
}) 

UPDATE: 如使用Array.some的意見建議是更好地在這裏:

return arr1.map((e1, i) => { 
    if (arr2.some(e2 => e2.id === e1.id)) { // If there's a match 
    return <div>Match</div> 
    } else { 
    return <div>No Match</div> 
    } 
}) 
+1

謝謝,第一個答案我看到了,它的工作完美。謝謝你解釋我的錯誤,幫助我瞭解我做錯了什麼:) – Jake

+2

而不是*過濾*,[*某些*](http://www.ecma-international.org/ecma-262/7.0/index .html#sec-array.prototype.some)可能更高效,因爲它會在第一次匹配時停止,並且不會創建無用的數組。 – RobG

+0

@RobG很棒的建議!我不知道'有些'。這當然更適合。 – SealedSaint

1

你可以使用第一個陣列上filter,並includes第二陣列上:

arr1 
    .filter(e => arr2.map(e2 => e2.id).includes(e.id)) 
    .map(e => return (<div>Match</div>)); 
1

你可以用香草JS這一個。當執行此操作循環中,檢查了比較你正在:

迭代(省略ID): ArrayOne VS ArrayTwo

  1. 1與3
  2. 2比較比較了4
  3. 3比較與未定義(將錯誤,因爲它的要求爲undefined.id)
  4. 4與未定義的比較(將錯誤,因爲它要求undefined.id)

如果您的元素是總是將按順序排列,您可以遍歷第一個數組並構建二進制搜索以快速查找第二個元素。這將您的時間複雜性帶到o(n * log(n)),並且從長遠來看會更好。如果你只是希望打MVP,你可以這樣做:

const myFilter = (arrayOne, arrayTwo) => { 
    return arrayOne.map((objectOne) => { 

    // Using findIndex over includes to be able to pass callback 
    // to compare the IDs 
    // returns -1 if not found 

    const matchIndex = arrayTwo.findIndex((objectTwo) => { 
     return objectOne.id === objectTwo.id 
    }) 


    if (matchIndex >= 0) { 
     return <div> Match </div> 
    } else { 
     return <div> NoMatch </div> 
    } 

    }) 
} 

你的時間複雜度將是這種做法o(n^2),但可能會根據您的情況最好的情況。您還可以使用臨時數據結構(例如Set)獲得o(n)時間,其折衷爲o(n)空間。

相關問題