搜索

首页  >  问答  >  正文

移除与数组值相等的对象的操作

<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粉985686557P粉985686557489 天前490

全部回复(2)我来回复

  • P粉809110129

    P粉8091101292023-09-06 17:33:17

    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)

    像这样?

    回复
    0
  • P粉790187507

    P粉7901875072023-09-06 09:46:39

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

    回复
    0
  • 取消回复