i have a object array and a normal array, i want to remove item in object array if it is equal to my normal array. it is confusing for me to do.
Here’s what i have tried so far
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 );
The expected output should be like this
var NewCountries =
[
{ChoicesID: 4, ChoicesName : 'angola'},
{ChoicesID: 5, ChoicesName : 'argentina'},
{ChoicesID: 6, ChoicesName : 'armenia'}
];
3
Answers
use
filter
and remove if theanswer
has it. created ananswerSet
to get O(1) lookup otherwise can useincludes
but includes is O(m) (m is no of elements in theanswer
array, n is elements incountries
array)with set
O(m) + O(n).O(1) = O(n) (given n>m)
with includes
O(n).O(m) = O(nm)
like this?