1

Let's say I have an array of objects and one of the properties of each object is TheID. Something like this:

TheArray[0].TheID = 34;
TheArray[1].TheID = 2352;
...

I'm looking to return the index of the array that contains the property TheID I'm looking for.

I have a classic for-loop:

for (i = 0; i < TheArray.length; i++) {
   if (TheArray[i].TheID = MagicNumber) { var TheIndex = i; } 
}
retun TheIndex;

This works but it still has to loop through the entire array, even after it found TheIndex.

How do you stop the loop after the it found TheIndex?

Thanks.

1
  • Throw it into a function, then return the variable. It'll drop out of the loop. Or use break. Commented Nov 22, 2011 at 21:43

4 Answers 4

3

You could use break to leave the loop:

var TheIndex;
for (var i = 0; i < TheArray.length; i++) {
   if (TheArray[i].TheID == MagicNumber) {
      TheIndex = i;
      break;
   } 
}
return TheIndex;
Sign up to request clarification or add additional context in comments.

Comments

0
if (TheArray[i].TheID = MagicNumber) { return i; }

Comments

0

Break; or return; within a loop to stop it once you have found what you are looking for. There is no other way to search arrays/objects for specific property values. You could consider re factoring your code entirely to avoid unnecessary performance sinks like this but that isn't always feasible.

Comments

0

Even though this is from a while ago, another alternative that might be useful if you do many such searches would be to loop once an index based on your search criteria.

e.g. do this once:

var idToIdx={};
for (var i = 0; i < TheArray.length; i++) {
   idToIdx['I'+TheArray[i].TheID] = i
   } 
}

and then just use for idToIdx['I'+ MagicNumber] as many times as you need.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.