skip to Main Content

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


  1. use filter and remove if the answer has it. created an answerSet to get O(1) lookup otherwise can use includes but includes is O(m) (m is no of elements in the answer array, n is elements in countries array)

    with set
    O(m) + O(n).O(1) = O(n) (given n>m)

    with 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)
    Login or Signup to reply.
  2. 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 NewCountries = countries.filter(o => !answer.includes(o.ChoicesName))
    
    console.log(NewCountries)
    

    like this?

    Login or Signup to reply.
  3. 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 filteredArray = countries.filter(
        (country) => !answer.includes(country.ChoicesName)
      );
      console.log(filteredArray);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search