skip to Main Content

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?

2

Answers


  1. It can be done, and, it needs a couple of steps as you are just not checking the duplicates.

    1. You need to identify the change in types
    2. You need to identify the additional did present
    3. combine the two to get the result

    Working code below

    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"}];
    
    
    // identify the type change
    var arr_c = arr_b.filter(({id:a, name:x, type: p}) => arr_a.some(({id:b, name:y, type:q}) => a === b && x === y && p!==q) );
    
    // identify the new id
    var arr_d = arr_b.filter(({id:a}) => !arr_a.some(({id:b}) => a === b));
    
    // merge the two
    var result = arr_c.concat(arr_d)
    
    console.log(result)
    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search