移除與數組值相等的物件的操作
P粉985686557
2023-09-05 20:56:36
<p>我有一個物件數組和一個普通數組,如果物件數組中的項等於普通數組中的項,我想要移除它。對我來說這很困惑。 </p>
<p>以下是我目前嘗試過的:</p>
<p>
<pre class="snippet-code-js lang-js prettyprint-override"><code>var countries =
[
{ChoicesID: 1, ChoicesName : 'afghanistan'},
{ChoicesID: 2, ChoicesName : 'albania'},
{ChoicesID: 3, ChoicesName : 'algeria'},
{ChoicesID: 4, ChoicesName : 'angola'},
{ChoicesID: 5, ChoicesName : 'argentina'},
{ChoicesID: 6, ChoicesName : 'armenia'}
];
var answer = ['afghanistan','albania','algeria'];
var ChoicesName = new Set(countries.map(d => d.ChoicesName));
var NewCountries = [...ChoicesName, ...answer.filter(d => !ChoicesName.has(countries.find(o => o.ChoicesName === answer)))];
console.log(NewCountries );</code></pre>
</p>
<p>預期輸出應該是這樣的:</p>
<pre class="brush:php;toolbar:false;">var NewCountries =
[
{ChoicesID: 4, ChoicesName : 'angola'},
{ChoicesID: 5, ChoicesName : 'argentina'},
{ChoicesID: 6, ChoicesName : 'armenia'}
];</pre></p>
像這樣?
使用
filter
並刪除如果answer
# 中存在它。建立一個answerSet
以進行O(1) 的查找,否則可以使用includes
,但includes
的時間複雜度為O(m)(其中m 是answer
陣列中的元素數量,n 是countries
陣列中的元素數量)使用 set
O(m) O(n).O(1) = O(n)(給定 n>m)
使用 includes
O(n).O(m) = O(nm)