0

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'}]
Sutirath
  • 61
  • 1
  • 1
  • 5

3 Answers3

0

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)
kennarddh
  • 2,186
  • 2
  • 6
  • 21
0

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]);
Sumit Sharma
  • 1,192
  • 1
  • 4
  • 18
-1

Perhaps You're looking for set's, take a look on: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

modzello86
  • 433
  • 7
  • 16
  • 1
    Your answer would benefit from giving an example on how OP would use a Set for this task (as it currently is, this is best suited as a comment and not an answer). – Nick Parsons May 14 '22 at 10:29