In my Angularjs application, I have created a JavaScript function to remove duplicate items from one array which also exist in another array. The function works by iterating through arr1 and checking if each item is present in arr2. If a match is found, the item is removed from arr1.
// Remove duplicate items from array1 based on array2
$rootScope.removeArrayDuplicated = function (arr1, arr2) {
console.log('before');
console.log(arr1);
for (var i = 0; i < arr2.length; i++) {
Inner: for (var j = 0; j < arr1.length; j++) {
if (arr2[i].name == arr1[j].name) {
console.log("inside " + arr2[i].name + " " + arr1[j].name);
arr1.splice(j, 1);
j--;
break Inner;
}
}
}
console.log('after');
console.log(arr1);
return arr1;
}
After running the function, I noticed that both the before and after arrays are displaying the same values. I suspect there might be an error in my logic. Could someone please help me identify and correct it?
*Note: The arrays consist of JSON objects.