1

I have tow arrays of object like this :

  const array1 = [
    { id: 1, name: 'A' },
    { id: 2, name: 'B' },
    { id: 3, name: 'C' }
  ]
  const array2 = [
    { id: 1, name: 'A' },
    { id: 2, name: 'B' }
  ]

I want another array from arry1 which contains those objects which are not in array2. like this :

[{ id: 1, name: 'C' }]

I tried this approach : var finalArray = array1.filter(function (obj) { return array2.indexOf(obj) === -1; }); But its not working. Please help me

3 Answers 3

1

try this :

  const array1 = [
    { id: 1, name: 'A' },
    { id: 2, name: 'B' },
    { id: 3, name: 'C' }
  ]
  const array2 = [
    { id: 1, name: 'A' },
    { id: 2, name: 'B' }
  ]
  
const array2Names = array2.map(e => e.name)

const arrayYouWant = array1.filter(e => array2Names.includes(e.name) === false)

The array2Names variable return an array like this : ['A','B'] The includes method allows us to know if the analyzed array contains the element in parentheses.

Sign up to request clarification or add additional context in comments.

Comments

0

We can use Array.filter and Array.find to get all the objects in array1, but not in array2.

We use .filter to find all the items in array1 that are not present in array2, using .find.

const array1 = [
    { id: 1, name: 'A' },
    { id: 2, name: 'B' },
    { id: 3, name: 'C' }
]

const array2 = [
    { id: 1, name: 'A' },
    { id: 2, name: 'B' }
]
  
const diff = array1.filter(x1 => !array2.find(x2 => {
    return x1.id === x2.id && x1.name === x2.name;
}));
  
console.log(diff);

Comments

0

const array1 = [
    { id: 1, name: 'A' },
    { id: 2, name: 'B' },
    { id: 3, name: 'C' }
  ]
  const array2 = [
    { id: 1, name: 'A' },
    { id: 2, name: 'B' }
  ]
  const arr = [... new Set(array1.filter(el => !array2.some(el2 => el2.id == el.id)))];
  console.log(arr);

1 Comment

you can this one as well. const arr = array1.filter(el => !array2.some(el2 => el2.id == el.id && el2.name == el.name))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.