Krishna Chaitanya
Krishna Chaitanya

Reputation: 2663

Javascript, how to match and get similar objects containing in two arrays?

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?

Upvotes: 1

Views: 117

Answers (1)

KJ Price
KJ Price

Reputation: 5984

You are correct when talking about efficiency, what you have above is a O(n^2) level of complexity as you have two "nested" loops. You want to run through each loop just one time.

First, I'd loop through the second array and create an object of this so that you can easily search by name:

var obj2 = {};
for (var i = 0; i < arr2.length; i++) {
    obj2[arr2[i].name] = arr2[i];
}

Then, loop through the first array and see if the name property exists in the new obj2 object we created:

var intersec = [];
for (var i = 0; i < arr1.length; i++) {
    if (obj2[arr1[i].name]) {
        intersec.push(arr1[i]);
    }
}

This solution will give you a O(2n) level of complexity...Much more efficient!

Upvotes: 2

Related Questions