移除與數組值相等的物件的操作
P粉985686557
P粉985686557 2023-09-05 20:56:36
0
2
461
<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>
P粉985686557
P粉985686557

全部回覆(2)
P粉809110129
var countries = 
[
{ChoicesID: 1, ChoicesName : '阿富汗'},
{ChoicesID: 2, ChoicesName : '阿尔巴尼亚'},
{ChoicesID: 3, ChoicesName : '阿尔及利亚'},
{ChoicesID: 4, ChoicesName : '安哥拉'},
{ChoicesID: 5, ChoicesName : '阿根廷'},
{ChoicesID: 6, ChoicesName : '亚美尼亚'}
];

var answer = ['阿富汗','阿尔巴尼亚','阿尔及利亚'];

var NewCountries = countries.filter(o => !answer.includes(o.ChoicesName))

console.log(NewCountries)

像這樣?

P粉790187507

使用 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)

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'];

const answerSet = new Set(answer)

const newCountries = countries.filter(c => !answerSet.has(c.ChoicesName))

console.log(newCountries)
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板