search

Home  >  Q&A  >  body text

Operation to remove objects equal to array value

<p>I have an object array and a normal array, and if an item in the object array is equal to an item in the normal array, I want to remove it. This is confusing to me. </p> <p>Here's what I've tried so far: </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>The expected output should look like this: </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粉985686557529 days ago520

reply all(2)I'll reply

  • 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)

    like this?

    reply
    0
  • P粉790187507

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

    Use filter and remove if it exists in answer. Create an answerSet for O(1) lookup, otherwise includes can be used, but the time complexity of includes is O(m) (where m is answer The number of elements in the array, n is countries The number of elements in the array)

    Use set
    O(m) O(n).O(1) = O(n) (given n>m)

    Use 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)

    reply
    0
  • Cancelreply