0

I am doing comparison between two arrays, I need to compare for each Array A 'id' with for each Array B 'id1'. If there is no match I need to pull out that particular object of Array A

Array - A

var A=[
  {
    "id": "xyz",
    "number": "123",
    "place": "Here",
    "phone": "9090909090"     
  },
  {
    "id": "abc",
    "number": "456",
    "place": "There",
    "phone": "9191919191"    
  },
 ]
 
 Array - B
 
 var B = [
 {
    "element1" : "ert",
    "id1":"iii",
    "element2":"erws",
    "element3":"234"
    
 }
,
 {
    "element1" : "uio",
    "id1":"xyz",
    "element2":"puy",
    "element3":"090"
 }
]

Using below -

var output = A.filter(x => B.some(y => x.id !== y.id1));
console.log(output);

Unable to perform inequality operation for the below code snippet. It is giving me complete Array A even though performing inequality operator Is anything I missing here

The output I am expecting here is


 [{
    "id": "abc",
    "number": "456",
    "place": "There",
    "phone": "9191919191"    
  },
 ]

Please help me with the suggestions to make this work in javascript.

Virat
  • 77
  • 1
  • 5
  • What have you tried to resolve the problem? Where are you stuck? Is there any error message given? – Nico Haase Jul 19 '21 at 13:09
  • 3
    @NicoHaase he has explained all of those questions of yours already – Celsiuss Jul 19 '21 at 13:11
  • No, the OP hasn't shared any debugging steps so far. Any current browser provides good capabilities to set a breakpoint within such an expression, such that the code can be executed step by step – Nico Haase Jul 19 '21 at 13:13
  • `var output = A.filter(x => !B.some(y => x.id === y.id1));` In OPs example, you would get all elements that has a non matching id, even if there was a matching id. – Celsiuss Jul 19 '21 at 13:17

1 Answers1

1

Credit to Ben west comment, A better performant solution.

You can compare two id with some(), once they are matched, it will return true from the some function. Therefore, the !some means you get a result set of the Array A which not matching with any records in the Array B.

var A = [ { id: "xyz", number: "123", place: "Here", phone: "9090909090", }, { id: "abc", number: "456", place: "There", phone: "9191919191", }, ]; var B = [ { element1: "ert", id1: "iii", element2: "erws", element3: "234", }, { element1: "uio", id1: "xyz", element2: "puy", element3: "090", }, ];

var output = A.filter(x => !B.some(y => x.id === y.id1));
console.log(output);

Another solution. You should use every instead of some Same logic above.

var A = [ { id: "xyz", number: "123", place: "Here", phone: "9090909090", }, { id: "abc", number: "456", place: "There", phone: "9191919191", }, ]; var B = [ { element1: "ert", id1: "iii", element2: "erws", element3: "234", }, { element1: "uio", id1: "xyz", element2: "puy", element3: "090", }, ];

var output = A.filter(x => B.every(y => x.id !== y.id1));
console.log(output);
ikhvjs
  • 5,316
  • 2
  • 13
  • 36