I’m using this JavaScript to iterate through an array and find a matching array element:
var remSize = [],
szString, remData, remIndex, i;
for (i = 0; i < remSize.length; i++) {
// I'm looking for the index i, when the condition is true
remSize[i].size == remData.size ? remIndex = i : remIndex = -1;
}
The array contains these “sizes”: ["34", "36", "38"...].
remData.size is the “size” I’m looking for (e.g. “36”).
I need to return the index i if the size I’m searching for is in the index. Otherwise I need to return -1. Is there a better way to do this?
To stop a
forloop early in JavaScript, you usebreak:That said, for this specific use case, you can use
Array‘sfindIndex(to find the entry’s index) orfind(to find the entry itself):findstops the first time the callback returns a truthy value, returning the element that the callback returned the truthy value for (returnsundefinedif the callback never returns a truthy value):findIndexdoes the same thing, but returns the index of the entry the callback returned a truthy value for or-1if it never does.(There’s also
somefunction, but it wouldn’t be appropriate here.)More about looping in my other answer here.