'I want to new array of 2 array is not equal data [duplicate]
I want to new array of 2 array is not equal data example
let a = [{id:1, name:"a"},{id:2, name:"b"},{id:3, name:"c"}];
let b = [{id:1, name:"a"},{id:2, name:"b"},{id:3, name:"c"}, {id:4, name:"d"}];
result
c = [{id:4, name:'d'}]
Solution 1:[1]
You can do this using filter() and includes() functions.
let a = [{id:1, name:"a"},{id:2, name:"b"},{id:3, name:"c"}];
let b = [{id:1, name:"a"},{id:2, name:"b"},{id:3, name:"c"}, {id:4, name:"d"}];
// b diff a
let resultA = b.filter(elm => !a.map(elm => JSON.stringify(elm)).includes(JSON.stringify(elm)));
// a diff b
let resultB = a.filter(elm => !b.map(elm => JSON.stringify(elm)).includes(JSON.stringify(elm)));
// show merge
console.log([...resultA, ...resultB]);
Solution 2:[2]
const a = [{id:1, name:"a"},{id:2, name:"b"},{id:3, name:"c"}]
const b = [{id:1, name:"a"},{id:2, name:"b"},{id:3, name:"c"}, {id:4, name:"d"}]
const bId = b.map(item => item.id)
const result = a.filter(item => bId.includes(item.id))
console.log(result)
Solution 3:[3]
Perhaps You're looking for set's, take a look on:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sumit Sharma |
| Solution 2 | kennarddh |
| Solution 3 | modzello86 |
