Javascript, Iterating through two arrays of objects and adding an item from one to another “if it doesn't exist”

Ask a question+

I have two arrays, one contains values as strings and the other like integers, as silly as it might be, but I got stuck on it, and I need a little help, I want to iterate through both, and if arr1 contains an item that doesn’t exist in arr2, it will be pushed to a newArray

here is what I tried

const arr1 = [
  {id: 1, user_id: 1},
  {id: 2, user_id: 2},
  {id: 3, user_id: 3},
  {id: 4, user_id: 4},

const arr2 = [
  {id: '1', user_id: '1'},
  {id: '2', user_id: '2'},
  {id: '3', user_id: '3'},

const newArray = []

for (const x of arr1) {
  for (const y of arr2) {
    if (x.id !== +y.id) {


this adds all items in arr1, what I want to be pushed to newArray instead is only the item that exists in arr1 and not in arr2

add comment

0 Answer

Your Answer