最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Difference of two arrays of objects with lodash - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question asked Nov 23, 2020 at 16:27 Ruan DuarteRuan Duarte 3854 silver badges19 bronze badges 1
  • 4 Its because object are not equal even if their contents are the same because they have different adresses in memory. – Talmacel Marian Silviu Commented Nov 23, 2020 at 16:33
Add a ment  | 

2 Answers 2

Reset to default 5

You can use xorBy to indicate a property used for parison:

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/npm/[email protected]/lodash.min.js"></script>

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));
发布评论

评论列表(0)

  1. 暂无评论