[javascript] Comparing two arrays of objects, and exclude the elements who match values into new array in JS

here is my use case in JavaScript:

I have two arrays of objects which have properties that match (id & name).

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'];

My goal is to have another array of objects containing only the elements which did not match. Like this:

var result = [
    {id:1, name:'Sandra'},
    {id:3, name:'Peter'}
];

I know that there is a way of doing this by going from 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, but I wonder is there any more elegant way, like using lo-dash or underscore or something similar.

Thank you!

The answer is


Check out difference and xor in lodash.


I have searched a lot for a solution in which I can compare two array of objects with different attribute names (something like a left outer join). I came up with this solution. Here I used Lodash. I hope this will help you.

var Obj1 = [
    {id:1, name:'Sandra'},
    {id:2, name:'John'},   
];

var Obj2 = [
    {_id:2, name:'John'},
    {_id:4, name:'Bobby'}
];

var Obj3 = lodash.differenceWith(Obj1, Obj2, function (o1, o2) {
    return o1['id'] === o2['_id']
});

console.log(Obj3);
//  {id:1, name:'Sandra'}

The same result can be achieved using Lodash.

_x000D_
_x000D_
var result1 = [_x000D_
    {id:1, name:'Sandra', type:'user', username:'sandra'},_x000D_
    {id:2, name:'John', type:'admin', username:'johnny2'},_x000D_
    {id:3, name:'Peter', type:'user', username:'pete'},_x000D_
    {id:4, name:'Bobby', type:'user', username:'be_bob'}_x000D_
];_x000D_
_x000D_
var result2 = [_x000D_
    {id:2, name:'John', email:'[email protected]'},_x000D_
    {id:4, name:'Bobby', email:'[email protected]'}_x000D_
];_x000D_
_x000D_
var result3 = _(result1) _x000D_
        .differenceBy(result2, 'id', 'name')_x000D_
        .map(_.partial(_.pick, _, 'id', 'name'))_x000D_
        .value();_x000D_
_x000D_
console.log(result3);
_x000D_
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

You can get the desired result applying a difference between both arrays using the properties "id" and "name" as a way to "link" elements between them. If any of those properties are different, the elements are considered different (improbably in your case because id seems to be unique).

Lastly, you have to map the result in order to "omit" the undesired properties of the object.

Hope it helps.


well, this using lodash or vanilla javascript it depends on the situation.

but for just return the array that contains the duplicates it can be achieved by the following, offcourse it was taken from @1983

var result = result1.filter(function (o1) {
    return result2.some(function (o2) {
        return o1.id === o2.id; // return the ones with equal id
   });
});
// if you want to be more clever...
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));

Here is another solution using Lodash:

var _ = require('lodash');

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]'}
];

// filter all those that do not match
var result = types1.filter(function(o1){
    // if match found return false
    return _.findIndex(types2, {'id': o1.id, 'name': o1.name}) !== -1 ? false : true;
});

console.log(result);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to underscore.js

Add property to an array of objects Comparing two arrays of objects, and exclude the elements who match values into new array in JS using lodash .groupBy. how to add your own keys for grouped output? Remove Duplicate objects from JSON Array Lodash .clone and .cloneDeep behaviors find the array index of an object with a specific key value in underscore Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined Map over object preserving keys Remove an item from array using UnderscoreJS Find by key deep in a nested array

Examples related to javascript-objects

Cannot read property 'style' of undefined -- Uncaught Type Error Is this a good way to clone an object in ES6? What’s the difference between “{}” and “[]” while declaring a JavaScript array? Comparing two arrays of objects, and exclude the elements who match values into new array in JS Converting JavaScript object with numeric keys into array From an array of objects, extract value of a property as array How to copy JavaScript object to new variable NOT by reference? Remove property for all objects in array Using curl POST with variables defined in bash script functions How to sum the values of a JavaScript object?

Examples related to lodash

Can't perform a React state update on an unmounted component Angular 4 HttpClient Query Parameters use Lodash to sort array of object by value How to group an array of objects by key Removing object properties with Lodash How to merge two arrays of objects by ID using lodash? Error: EACCES: permission denied Replacing objects in array lodash: mapping array to object Correct way to import lodash