0

I try to return difference between two arrays of objects using array.filter() and array.some() but I can't get the desired result. Maybe I need to have the same attributes id and name into this two arrays.

Here my two arrays

let array1 = [
  { 'id': 1, 'name': 'apple' }, 
  { 'id': 2, 'name': 'blueberry' }
]

let array2 = [
  { 'id': 1, 'name': 'apple' }, 
  { 'id': 2, 'name': 'blueberry' }, 
  { 'name': 'banana' }
]

Here my code

let difference = array1.filter(x => !array2.some(y => x.name === y.name))

console.log(difference) // empty but I want this -> [{ 'name': banana }]
Bonsai
  • 346
  • 3
  • 17
  • Please have a look at this https://stackoverflow.com/questions/21987909/how-to-get-the-difference-between-two-arrays-of-objects-in-javascript – chintuyadavsara Jul 01 '19 at 12:48
  • The "problem" is the different `length` between them. – Ele Jul 01 '19 at 12:50
  • You are taking difference of array2 from array1, the result would be empty. For desired result, please take difference of array1 from array2. – kamran Jul 01 '19 at 12:54
  • 1
    let difference = array2.filter(x => !array1.some(y => x.name === y.name)) – kamran Jul 01 '19 at 12:56

0 Answers0