Compare object array and delete repeat

Asked

Viewed 55 times

-4

I need to make a method where I receive from the frontend an array of objects, and compare with the array of objects q have in the database, so I perform the query in the database that is data1 and data 2 is what comes from the frontend, I need to check if in data1 there is the id of the data2 and if it exists delete the position to return to the front what he did not send

const data1 = [
        { id: 1, nome: 'fulano' },
        { id: 2, nome: 'ciclano' },
      ];

const data2 = [
        { id: 1, nome: 'fulano' },
        { id: 3, nome: 'joao' },
      ];

What I need to do is check that in the data1 array there is an object with the same ID as the data2 array and if there is a removal of the data1 id and name. what I’ve tried is:

const filtered = data1.filter(item => data2.filter(item1 => item1.d === data.id).pop());

the expected return is this:

const dataFiltered = [
        { id: 2, nome: 'ciclano' },
        { id: 3, nome: 'joao' },
      ];

  • 3

    The code that you tried nor even to be executed. What should be data? Is a Binding undefined that is completely out of context there.

  • are data q comes from the database, I’m making a conferencing app, then the front sends an array of objects and I need to compare this array with the q I have in the database and return to the user only what he n checked know?

1 answer

-2


Hello, good afternoon, sir! From what I understand, you would like to "map" an array, check the elements in it, and if the element of array1 equals the element of array2, you remove it.

const data1 = [
  { id: 1, nome: 'fulano' },
  { id: 2, nome: 'ciclano' }
];

const data2 = [
  { id: 1, nome: 'fulano' },
  { id: 3, nome: 'joao' }
];

const dataFiltered = [];

for(var i = 0; i < data1.length; i++){
  if(data1[i].id != data2[i].id){
      dataFiltered.push(data1[i]);
      dataFiltered.push(data2[i]);
  }
};

console.log(dataFiltered);//[ { id: 2, nome: 'ciclano' }, { id: 3, nome: 'joao' } ]

I made that code and I hope I helped!

NOTE: this code will only work properly if the arrays are the same "size"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.