Skip to content

JavaScript compares two arrays of objects for matches | Code

  • by

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

Javascript compares two arrays of objects for matches

For simple example, code result1 compares each object with the objects of result2, then compares their keys, and if they do match, put the values in another object and then push it into a 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading