Skip to content

JavaScript compares two arrays of objects for matches | Code

  • by

Just using the Array iteration methods to compares two arrays of objects for matches in JavaScript. Filter out items for first array and use reduce to make objects with only the required properties and map to apply this to the filtered array as a whole.

Javascript compares two arrays of objects for matches

Simple example code result1 compare each object with the objects of result2, then compare their keys, and if did’n match, put the values in another object then push it in new array.

<!DOCTYPE html>
<html lang="en">
<body>
  <script>

   var result1 = [
   {id:1, name:'Sandra', type:'user', username:'sandra'},
   {id:2, name:'John', type:'admin', username:'johnny2'},
   {id:3, name:'Peter', type:'user', username:'pete'},
   {id:4, name:'Bobby', type:'user', username:'be_bob'}
   ];

   var result2 = [
   {id:2, name:'John', email:'[email protected]'},
   {id:4, name:'Bobby', email:'[email protected]'}
   ];

   var props = ['id', 'name'];

   var result = result1.filter(function(o1){
    
    return !result2.some(function(o2){
      return o1.id === o2.id;        
    });
  }).map(function(o){
   
    return props.reduce(function(newo, name){
      newo[name] = o[name];
      return newo;
    }, {});
  });

  console.log(result)

</script>
</body>
</html>

Output:

Javascript compares two arrays of objects for matches

Using lodash external libraries

var result1 = [
    {id:1, name:'Sandra', type:'user', username:'sandra'},
    {id:2, name:'John', type:'admin', username:'johnny2'},
    {id:3, name:'Peter', type:'user', username:'pete'},
    {id:4, name:'Bobby', type:'user', username:'be_bob'}
];

var result2 = [
    {id:2, name:'John', email:'[email protected]'},
    {id:4, name:'Bobby', email:'[email protected]'}
];

var result3 = _(result1) 
        .differenceBy(result2, 'id', 'name')
        .map(_.partial(_.pick, _, 'id', 'name'))
        .value();

console.log(result3);
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>

Do comment if you have any doubts or suggestions on this Js compares array code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *