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

All I have to do is compare two arrays of objects and remove the elements in the second 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 do not 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}]; 
+8
javascript object arrays
source share
7 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; } } } 
+15
source share

You just need to break the inner loop when a match is found:

 if (a[i].name == b[j].name) { b.splice(j, 1); break; } 
+3
source share

Your problem is that splice() will change the length of the array, so your pre-calculated len value will be too large and inside the loop you will try to access undefined elements.

A possible solution would be to use the filter() method:

 function remove_duplicates(a, b) { b = b.filter( function( item ) { for( var i=0, len=a.length; i<len; i++ ){ if( a[i].name == item.name ) { return false; } } return true; }); console.log(a); console.log(b); } 

Script example

+2
source share

Try the following:

You start a cycle from 0 .

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

Screenshot

+1
source share

Instead of using two loops, you can 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 can use the forEach function

 a.forEach(function(item, index, array) { var ItemIndex = b.findIndex(b => b.name === item.name); a.splice(ItemIndex, 1) } 
+1
source share

The main reason is that you directly connect the elements from the array b when you are in the for loop, and the precondition - a and b have the same number of elements.

0
source share

compare and delete in the array of the object. Typically an array of an object's data type may be typeOf - object.So, which we need to convert to JSON stringify, and then check the condition.

 for(var i=0; i < a.length; i++) { for(var j=0; j < b.length; j++) { if(JSON.stringify(a[i]) == JSON.stringify(b[j])) { a.splice(i, 1); } } } 
0
source share

All Articles