Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two arrays of objects and remove items in the second one that have the same property value

All I need to do is compare two arrays of objects and remove items in the second one that have the same property value. For example:

var a = [{'name':'bob', 'age':22}, {'name':'alice', 'age':12}, {'name':'mike', 'age':13}];
var b = [{'name':'bob', 'age':62}, {'name':'kevin', 'age':32}, {'name':'alice', 'age':32}];

function remove_duplicates(a, b) {
    for (var i = 0, len = a.length; i < len; i++) {
        for (var j = 0, len = b.length; j < len; j++) {
            if (a[i].name == b[j].name) {
                b.splice(j, 1);
            }
        }
    }

    console.log(a);
    console.log(b);

}

console.log(a);
console.log(b);

remove_duplicates(a,b);

I cannot understand why this does not work and instead gives:

Uncaught TypeError: Cannot read property 'name' of undefined

What I expected was the following content in b:

[{'name':'kevin', 'age':32}];
like image 773
raben Avatar asked Jul 24 '13 09:07

raben


People also ask

How do you compare two arrays the same?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.

How do you know if two arrays of objects are equal?

equals(Object[] a, Object[] a2) method returns true if the two specified arrays of objects are equal to one another. The two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal.


2 Answers

FIDDLE

 for (var i = 0, len = a.length; i < len; i++) { 
        for (var j = 0, len2 = b.length; j < len2; j++) { 
            if (a[i].name === b[j].name) {
                b.splice(j, 1);
                len2=b.length;
            }
        }
    }
like image 153
Snippet Avatar answered Oct 28 '22 22:10

Snippet


Instead of using two loops you might also use the findIndex function:

for (var i = 0, len = a.length; i < len; i++) {
    var ItemIndex = b.findIndex(b => b.name === a[i].name);

    a.splice(ItemIndex, 1)
}

Or if you want to go completely without using a loop you might use the forEach function

a.forEach(function(item, index, array) {
    var ItemIndex = b.findIndex(b => b.name === item.name);

    a.splice(ItemIndex, 1)
}
like image 21
Geole Avatar answered Oct 28 '22 22:10

Geole