Operation to remove objects equal to array value
P粉985686557
2023-09-05 20:56:36
<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>
like this?
Use
filter
and remove if it exists inanswer
. Create ananswerSet
for O(1) lookup, otherwiseincludes
can be used, but the time complexity ofincludes
is O(m) (where m isanswer
The number of elements in the array, n iscountries
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)