Friday, 15 March 2013

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


I have two arrays of objects I want to check the list of objects present in an array based on name. [Name: "somebody", age: 30}] arr1 intersec arr2 = [[The name of "krishna", {age: 27}, {name: "chandan" Name: First of all, I try to iterate on the arrays and find similar items by the name like below

 > int intersec = []; (Var i = 0; i & lt; arr1.length; i ++) {for (var j = 0; j & lt; arr2.length; j ++) {if (arr1 [i] .name = == arr2 [j] name) {intersec.push (arr1 [i]); Later I thought this code would be complicated if the size of the data increases. 

So I came up with another argument where I organize arr1 and repeat on arr2 and get the name and check it on stringify-ed arr1 using indexOf function whether it exists.

  var exp = "name: \" "+ arr2 [i] .name +" \ ""; StringArr1.indexOf (sum);  

I want to know which is efficient and are there any other efficient ways to do this?

You are right when talking about efficiency, what's up to you O (N ^ 2) Level is complex because you have two "nested" loops, you want to run just once through each loop.

First of all, I will loop through the second array and make the purpose of this so that you can easily search by name:

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

Again, Loop through the first array and see if the new obj2 object in the name property that we have created:

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

This solution will give you the level of o (2n) complexity ... much more efficient!


No comments:

Post a Comment