This question is inspired from competing answers on this question: indexOf with multiple arguments
The user wanted to know an efficient way to test an array for the existence of one or more integers given in an array. Specifically, given an array and the numbers 123
, 124
, and 125
, how can you tell if one or more of these integers exists in the given array. Two solutions were suggested:
Using indexOf()
:
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var exists = array.indexOf(123) !== -1 || array.indexOf(124) !== -1 || array.indexOf(125) !== -1;
Or, using some()
:
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var exists = array.some(function(item) {
return item === 123 || item === 124 || item === 125;
});
Both the ECMA-262 algorithms for indexOf()
and some()
short-circuit when finding a successful match, but I would have thought that the some()
implementation would be faster when there are no matches. However, another user pointed out that the indexOf()
solution is faster.
How is the indexOf()
code more efficient even though it must iterate over the array more times?
.indexOf
lacks the overhead of calling a function.some
is probably more efficient for larger arrays. – Ludicrous