Reputation: 385
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
Upvotes: 2
Views: 3590
Reputation: 18197
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>
Upvotes: 5
Reputation: 1736
Its because object are not equal even if their contents are the same because they have different adress in memory.
You can try something like this:
const results = _.xor(A1.map(object=> JSON.stringify(object)), A2.map(object=> JSON.stringify(object))).map(item => JSON.parse(item));
Upvotes: 3