Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index of an object inside an array of objects?

I have a JavaScript array of objects like this:

box[0] = {...}
box[1] = {...}
box[2] = {...}
...
box[499] = {...}

This objects are generated by the same constructor and added to the array inside a loop. The objects have methods in the prototype which need to know the object's index in the array to do their stuff. Currently what I am doing is to set a property called id inside each object when I create it inside the loop, equal to the array index. Something like this:

box[i].id = i;

However I am not totally satisfied with this because each time I reorder the array using sort() I have to run a loop to update the id properties with the new index values.

My question is if there is a way to know inside an object its index in the array, without having to set the id property, hope you can help me.

Thanks in advance.

like image 835
VerizonW Avatar asked Jan 21 '11 03:01

VerizonW


2 Answers

I don't think a function inside an object in the Array is going to be aware of the index of the Array that is referencing it.

Because each item in the Array is simply pointing to that object in memory, there could conceivably be dozens of Array items, variables, Object properties, etc that reference that same object, so the function (or the object that contains the function) wouldn't know which back reference you're hoping to make.

I'm guessing you'll be stuck doing what you're doing if you need to know its index in the Array.

I suppose that function could call indexOf() against the Array since it returns an index, but that would require some overhead for each call, and you'll need to added it for unsupported browsers.

theArr.indexOf( this ); // assuming the function was called from the context
                        //   of the object in question
like image 50
user113716 Avatar answered Sep 27 '22 18:09

user113716


Why don't you add a unique property on each object and use that property to lookup the indexOf that Object.

If you have a constructor you can add an _id and then lookup that id using:

function getIndex(box, objectId) {
   var index = box.map(function(e) { return e._id; }).indexOf(objectId);
   return index;
}

This will work even if you sort the array, but you need to keep the id unique.

Array.prototype.map is not available on IE7 or IE8. ES5 Compatibility

btw, I don't like this solution but it will work on your problem :)

like image 31
German Attanasio Avatar answered Sep 27 '22 17:09

German Attanasio