Konrad Kahl Konrad Kahl - 1 year ago 70
Javascript Question

Best way to find index of exact same object in object Array (key is dynamic)

Let's say I have dynamically loaded object each time with different properties and an array of objects of that type:

var obj = {name: someValue, key: someValue2};
var objArray = [{name: someValue, key: someValue2},{name: someValue, key: someValue3}];

I want to find index of objArray which contains the obj. Some elements of objArray can have the same name property but different key property so searching through obj.name is not an option. So far I came up with this solution:

var keys = [];

_.forEach(Object.keys(obj), function(key) {
keys.push(key, obj[key])

var index = _.findIndex(objArray, keys);

This works fine and all but I am looking for something with better performance because this objArray can be very large.

So the question is: Is there a better way to find index of exact same object in object Array?

I forgot to mention that the names of the keys are not specified and can vary each time.

Answer Source

I can think of 2 approaches for doing this:

1.) What would speed up the process (especially if you got large array and large objects) is to create some kind of unique key for every object and map it to let's say property called: hash. If you wanna keep it vanilla, the best way to do that might be using the String.hashCode() method.

Iterate trough object OWN (check hasOwnProperty) properties and concat into single string both property name and then ### and then value and then %%% in between.

Then enhance your object with property hash like:

myObj.hash = String.hashCode(StringOfNamesAndValues);

Now iterate trough your array using for, and compare obj.hash to objArray[index].hash

Once they match you fond your object, store the index :)

If your object and one in the array don't have to be EXACTLY the same object but only a subset needs to be same. Instead using all property names in hash generation, use only the names and values of properties you wanna to be same. Compare hashes made in that way - voila!

2.) More brutish way would be to make object equal function that takes 2 objects and compares all the properties and values of respective properties. Now iterate trough array using that function. Pass your object and array object as parameters. If it returns that comparison is true, store index.

The bigger the objects are the slower this works.The bigger array is the slower this works. The more time you search for same objects slower this works (you compare every time instead making hash once).

Also, if you are having a very large set of object, and search often but add or remove to it sparsely, consider ordering the array in order considering hash values. Then use binary tree search for that hash to find appropriate object instead iterating from start to end each time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download