Thursday, 1 June 2017

Best way to find needed element in array of objects

I have array of objects of my class. My class have variable for name that is unique for every object created. Now, I want to find, say, object in array that has a name "test". I wanted to try something like creating second array with just names as elements and when I create new object in my first array to create object in second array so that they share index number. Something like this:

arrayOfObjects.push(new obj("test"));
arrayOfNames.push("test");

function findIndexNumberOf(name){
    for(var i = 0; i < arrayOfNames.length; i++){
        if(arrayOfNames[i] === name)
        return i;
    }
}

But I think that this is pretty robust solution so I'm wondering is there better/smarter/faster way of doing this.



via Slay29

No comments:

Post a Comment