I have two array of objects. I want to check the list of objects from array one existing in array two by name.
arr1 = [{name: "krishna", age: 27}, {name: "chandan", age 30}]
arr2 = [{name: "krishna", age: 27}, {name: "chandan", age 30}, {name: "someone", age: 30}]
arr1 intersec arr2 = [{name: "krishna", age: 27}, {name: "chandan", age 30}]
First I tried to iterate over the arrays and find the similar objects by name like below
var intersec = [];
for(var i = 0; i < arr1.length; i++) {
for(var j = 0; j < arr2.length; j++) {
if(arr1[i].name === arr2[j].name) {
intersec.push(arr1[i]);
}
}
}
Later I thought this code will become complicated if the data size grows.
So I came up with another logic where I stringify arr1 and iterate over arr2 and get the name and use indexOf function on the stringify-ed arr1 to check if it exists.
var exp = "name: \""+arr2[i].name+"\"";
stringArr1.indexOf(exp);
I want to know which one is efficient and are there any other efficient ways to do the same?