1

I have two JSON arrays like this :

var modelType = [
    {   'id' : 3,  'name': 'eR_Beta'},
    {   'id' : 12, 'name': 'eR_Studio'},
    {   'id' : 6,  'name': 'eR_OFF'},
    {   'id' : 9,  'name': 'eR_Schalte'}
];

var data = [
    {id: 12}
    {id: 6}
]

I would like to compare these arrays with "id" as key and get the not matching objects to another array like this :

var output = [
    {   'id' : 3,  'name': 'eR_Beta'},
    {   'id' : 9,  'name': 'eR_Schalte'}
]
vsam
  • 533
  • 3
  • 23
  • Possible duplicate of (Compare two arrays of objects and remove items in the second one that have the same property value)[https://stackoverflow.com/questions/17830390/compare-two-arrays-of-objects-and-remove-items-in-the-second-one-that-have-the-s] – Mara Black Oct 22 '19 at 13:06

2 Answers2

8

It is possible to do this through filter() and some() functions and logical not operator !:

var modelType = [{
    'id': 3,
    'name': 'eR_Beta'
  },
  {
    'id': 12,
    'name': 'eR_Studio'
  },
  {
    'id': 6,
    'name': 'eR_OFF'
  },
  {
    'id': 9,
    'name': 'eR_Schalte'
  }
];

var data = [{
    id: 12
  },
  {
    id: 6
  }
]

const result = modelType.filter(f =>
  !data.some(d => d.id == f.id)
);
console.log(result);
Constantin Groß
  • 10,719
  • 4
  • 24
  • 50
StepUp
  • 36,391
  • 15
  • 88
  • 148
  • Just out of curiosity, I did a jsperf comparing your and my (now deleted) approach. And oh boy is yours faster! ;-) https://jsperf.com/diff-of-array-of-objects-by-id – Constantin Groß Oct 22 '19 at 13:24
  • @ConstantinGroß wow! Thansk!:) So great performance!:) `some` function is really awesome!:) – StepUp Oct 22 '19 at 13:32
0
function isEqual() 
{ 
 var a = [1, 2, 3, 5]; 
 var b = [1, 2, 3, 5]; 
  // if length is not equal 
  if(a.length!=b.length) 
   return "False"; 
  else
  { 
  // comapring each element of array 
   for(var i=0;i<a.length;i++) 
   if(a[i]!=b[i]) 
    return "False"; 
    return "True"; 
  } 
}   var v = isEqual(); 
document.write(v); `