Search code examples
javascriptreact-hookslodash

Difference of two arrays of objects with lodash


I have the following code inside my useEffect in reactJS

const A1 = [{id: 1, nome: "Ruan"}, {id: 2, nome: "Gleison"}]
const A2 = [{id: 2, nome: "Gleison"}, {id: 3, nome: "Geraldo"}]

const results = _.xor(A1, A2);

console.log(results)

The logic of lodash is _.xor is to return the difference between the two arrays, however, that is not what is happening

The return I get is as follows

0: Object {id: 1, nome: "Ruan"}
1: Object {id: 2, nome: "Gleison"}
2: Object {id: 2, nome: "Gleison"}
3: Object {id: 3, nome: "Geraldo"}

I appreciate all efforts to help


Solution

  • You can use xorBy to indicate a property used for comparison:

    const A1 = [{id: 1, nome: "Ruan"}, {id: 2, nome: "Gleison"}]
    const A2 = [{id: 2, nome: "Gleison"}, {id: 3, nome: "Geraldo"}]
    
    const results = _.xorBy(A1, A2, 'id'); // or 'nome'
    
    console.log(results)
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>