Difference between two arrays with Typescript or ES6

Asked

Viewed 397 times

0

How can I get the difference between two Arrays of objects using TypeScript or ES6?

I tried to do using SET:

   let arr1 = new Set(lista1);
   let arr2 = new Set(lista2);
   let difference = new Set(
       [arr1 ].filter(x => !arr2.has(x)));

But it didn’t work, that’s the result I get: inserir a descrição da imagem aqui

That way the values are not listed, maybe it’s not the most appropriate way to do what I want.

  • Can you give an example of what arrays have inside and how you want the result of comparison? Because there are different ways to do it... do you want the differences in one of them? in both? are you comparing strings or objects? etc... Do you need to use Set or are they "normal" arrays? Have you tried let diff = arr1.filter(x => arr2.indexOf(x) == -1);?

1 answer

2


I solved the problem as follows:

let mapChamada = chamada.map(item => item.Matricula);
let mapPessoa = pessoas.map(item => item.Matricula);

let diff = mapChamada.map((Matricula, index) => {
  if (mapPessoa.indexOf(Matricula) < 0) {
    return chamada[index];
  }
}).concat(mapPessoa.map((Matricula, index) => {
  if (mapChamada.indexOf(Matricula) < 0) {
    return pessoas[index];
  }
})).filter(item => item != undefined);

console.log(diff);

Both of me arrays are these:

let chamada= [{
      Matricula: 434,
      Nome: 'Diego Augusto',
      PessoaId: 'bc61b0a1-2b8e-4c93-a175-21949ff2b240'
}];

let pessoas = [{
     Matricula: 434,
     Nome: 'Diego Augusto',
     PessoaId: 'bc61b0a1-2b8e-4c93-a175-21949ff2b240'
  }, {
     Matricula: 431,
     Nome: 'Crislayne',
     PessoaId: '11576497-7632-4c1b-9806-fed24b7608c2'
  }];

The result of the difference was:

diff [{
     Matricula: 431,
     Nome: 'Crislayne',
     PessoaId: '11576497-7632-4c1b-9806-fed24b7608c2'
  }];

Browser other questions tagged

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