Operation to remove objects equal to array value
P粉985686557
P粉985686557 2023-09-05 20:56:36
0
2
441
<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粉985686557
P粉985686557

reply all(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)

like this?

P粉790187507

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!