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}];
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.
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.
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;
}
}
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With