0

I am looking for a simple solution to compare just the "id" values and "type" in from two different arrays of objects as the following:

var arr_a = [
  { id: 1, name: "thumbler", type: "add" },
  { id: 2, name: "spoon", type: "add" },
  { id: 3, name: "plate", type: "add" },
];

var arr_b = [
  { id: 1, name: "thumbler", type: "remove" },
  { id: 2, name: "spoon", type: "add" },
  { id: 3, name: "plate", type: "add" },
  { id: 4, name: "fork", type: "add" },
];

and I wanna a result like this:

var arr_c = [
  { id: 1, name: "thumbler", type: "remove" },
  { id: 4, name: "fork", type: "add" },
];

I tried to use filter and some (from here) but doesn't work:

var arr_c = arr_b.filter(
  (x) =>
    arr_a.filter((y) => y.id === x.id && y.action_type === x.action_type)
      .length > 0
);

Any suggestions?

Agrim Singh
  • 499
  • 2
  • 13
Febry Fairuz
  • 521
  • 1
  • 10
  • 27

1 Answers1

1

You can use every and some methods of the array to achieve your result. See the snippet below.

let arr_c = arr_b.filter(a => arr_a.some(a1 => a1.id === a.id && a.type !== a1.type) || arr_a.every(a1 => a1.id !== a.id))

Full working code:-

var arr_a = [{id:1, name:"thumbler", type:"add"},
             {id:2, name:"spoon", type:"add"},
             {id:3, name:"plate", type:"add"}];

var arr_b = [{id:1, name:"thumbler", type:"remove"},
             {id:2, name:"spoon", type:"add"},
             {id:3, name:"plate", type:"add"},
             {id:4, name:"fork", type:"add"}];
var arr_c = arr_b.filter(a => arr_a.some(a1 => a1.id === a.id && a.type !== a1.type) || arr_a.every(a1 => a1.id !== a.id));

console.log(arr_c);
Shikhar Awasthi
  • 1,172
  • 1
  • 3
  • 13