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.