javascript indexof
javascript indexof is two methods. String.prototype.indexOf searches for a substring. Array.prototype.indexOf searches for an element. Both return the index of the first match, counting from 0, or -1 when there is no match.
const phrase = "red green red";
phrase.indexOf("red");
phrase.indexOf("green");
phrase.indexOf("blue");
The first call returns 0, because "red" starts at the beginning. The second returns 4, where "green" starts. The third returns -1.
const names = ["ada", "bea"];
names.indexOf("bea");
names.indexOf("ada");
names.indexOf("cy");
The first call returns 1. The second returns 0. The third returns -1.
A string search can match part of a longer string. "red green".indexOf("ee") returns 6. An array search has to match a whole element, so ["red", "green"].indexOf("ee") returns -1.
The string method turns the search value into a string before it looks. "room 5".indexOf(5) returns 5, because 5 becomes "5". The array method does not convert the search value. ["1", "2"].indexOf(1) returns -1, because 1 !== "1".
Omit the argument, and the two methods disagree. "say undefined".indexOf() looks for the text "undefined" and returns 4. ["undefined"].indexOf() compares the element with the value undefined, so it returns -1. [undefined].indexOf() returns 0.
The string search is case-sensitive. "Red".indexOf("red") returns -1. You can lowercase a copy and search that copy.
const label = "Red";
label.toLowerCase().indexOf("red");
toLowerCase() returns "red", and indexOf("red") on that copy returns 0. The index belongs to the lowercased string. It lines up with label here because lowercasing did not change the length. It does not always. "İ".toLowerCase() is two code units long, while "İ" is one, so an index into the lowercased copy can point at a different place than the same count into the original.
A match at index 0 is a real match. if (names.indexOf("ada")) does not run, because 0 is falsy. Test the miss value instead. names.indexOf("ada") !== -1 is true.
The second argument
Both methods take an optional second argument, the index where the search starts. It defaults to 0. The string parameter is position. The array parameter is fromIndex. fromIndex is converted to an integer.
| Start value | String position | Array fromIndex |
|---|---|---|
| Negative | Treated as 0 | length + fromIndex, and the search still walks toward the end. If that sum is still negative, the search starts at 0. |
| At or past the length | A non-empty search returns -1 | Returns -1 |
const phrase = "red green red";
phrase.indexOf("red", 1);
phrase.indexOf("e", -5);
phrase.indexOf("red", 20);
"red" at the start is behind 1, so the first call finds the later "red" and returns 10. A negative position is treated as 0, so the second call returns 1, the first "e". 20 is past the length of phrase, so the third call returns -1.
const names = ["ada", "bea", "ada"];
names.indexOf("ada", 1);
names.indexOf("bea", -2);
names.indexOf("bea", -10);
names.indexOf("ada", 3);
The first call skips the "ada" at 0 and returns 2. names has length 3, so -2 starts the search at 1, and the second call returns 1. -10 + 3 is still negative, so the third call starts at 0 and also returns 1. 3 is the length, so the fourth call returns -1 and does not look at any element.
Strict equality and NaN
Array indexOf uses strict equality, the same comparison as ===. The value and the type both have to match. null does not match undefined.
const row = [1, "1", null];
row.indexOf("1");
row.indexOf(1);
row.indexOf(undefined);
The first call returns 1. The second returns 0. The third returns -1.
NaN is not strictly equal to itself, so indexOf cannot find it.
[NaN].indexOf(NaN);
That call returns -1. The array does contain NaN.
Objects are compared by reference. Two objects with the same properties are still two objects.
const item = { id: 1 };
[item].indexOf(item);
[{ id: 1 }].indexOf({ id: 1 });
The first call returns 0, because the search value is the same object stored in the array. The second returns -1.
Sparse arrays and empty strings
Array indexOf skips empty slots. A hole is not a stored undefined.
const sparse = [1, , 3];
sparse.indexOf(undefined);
const explicit = [1, undefined, 3];
explicit.indexOf(undefined);
sparse has no element at index 1. The search skips that slot and returns -1. explicit stores undefined at index 1, so the second search returns 1.
The same method works on an array-like object. It reads length, then the integer keys below that length.
const arrayLike = { length: 3, 0: "a", 1: "b", 2: "c", 3: "d" };
Array.prototype.indexOf.call(arrayLike, "b");
Array.prototype.indexOf.call(arrayLike, "d");
The first call returns 1. The property 3 is past length, so the second call returns -1.
An empty search string follows a different rule from a normal substring. With no second argument, or with a second argument inside the string, the result is that start position. If the start is at or past the length, the result is the length.
"hello".indexOf("");
"hello".indexOf("", 3);
"hello".indexOf("", 5);
"hello".indexOf("", 8);
"hello".indexOf("h", 5);
Those calls return 0, 3, 5, 5, and -1. The last search is not empty, and the start is the length of "hello", so it returns -1.
An array has no empty-string rule. [""].indexOf("") returns 0. ["hello"].indexOf("") returns -1.
Finding every match
indexOf stops at the first match. To collect the rest, call it again with a start just after the match you found. The search string has to be non-empty.
const phrase = "red green red";
const hits = [];
let from = phrase.indexOf("red");
while (from !== -1) {
hits.push(from);
from = phrase.indexOf("red", from + 1);
}
from starts at 0. The loop stores 0, then searches from 1 and gets 10. It stores 10, then searches from 11 and gets -1. The loop stops. hits is [0, 10].
The array method uses the same loop.
const names = ["ada", "bea", "ada"];
const nameHits = [];
let at = names.indexOf("ada");
while (at !== -1) {
nameHits.push(at);
at = names.indexOf("ada", at + 1);
}
at is 0, then 2, then -1. nameHits is [0, 2].
An empty string never produces -1. "ab".indexOf("") returns 0, "ab".indexOf("", 1) returns 1, "ab".indexOf("", 2) returns 2, and "ab".indexOf("", 3) returns 2 again. Add 1 and search once more, and the result stays at the length, so a while (from !== -1) loop does not end.
indexOf, includes, and findIndex
includes answers yes or no. findIndex returns an index, and it uses a function instead of ===.
| Returns | How it matches | NaN in an array | Empty slots | |
|---|---|---|---|---|
indexOf | The index, or -1 | A string searches for a substring and coerces the search value. An array uses ===. | Not found | Skipped |
includes | true or false | A string searches for a substring and coerces the search value. An array uses SameValueZero, which matches === except that NaN counts as equal to NaN. | Found | Read as undefined |
findIndex | The index, or -1 | The callback returns a truthy value | Found when the callback says so | The callback is called with undefined |
[NaN].includes(NaN);
[1, , 3].includes(undefined);
[1, , 3].indexOf(undefined);
[NaN].findIndex((value) => Number.isNaN(value));
[{ id: 1 }, { id: 2 }].findIndex((item) => item.id === 2);
"red green".includes("green");
"red green".indexOf("green");
includes(NaN) returns true. includes(undefined) on the sparse array returns true, and indexOf(undefined) on that same array returns -1. findIndex returns 0 for the NaN array. The object search returns 1, because item.id === 2 is true for the second object. "red green".includes("green") returns true, and indexOf("green") returns 4.
Use indexOf when you need the position of a substring or of an element compared with ===. Use includes when the position does not matter. Use findIndex when the match depends on a property or on NaN.
Repeated lookups
Array indexOf walks from the start index and stops at the first match. A miss checks every index from that start through the end, so the work grows with the array.
A Set or a Map is a better fit when you ask the same large list many times. The specification requires both to provide average access that is sublinear in the number of elements. That can be a hash table, which is constant time on average, or a tree, which is logarithmic. You pay for one walk when you build the collection. Later lookups do not scan the array.
const ids = ["a1", "b2", "c3", "a1"];
const idSet = new Set(ids);
idSet.has("c3");
idSet.has("z9");
new Set(ids) keeps one copy of "a1". has("c3") returns true. has("z9") returns false. A set does not store the index.
Keep the first index in a Map when you still need the position.
const firstIndex = new Map();
ids.forEach((id, index) => {
if (!firstIndex.has(id)) {
firstIndex.set(id, index);
}
});
firstIndex.get("a1");
firstIndex.get("c3");
firstIndex.get("z9");
The has check stores "a1" only at 0, so the later "a1" does not overwrite it. get("a1") returns 0. get("c3") returns 2. get("z9") returns undefined.
The set and the map are copies. A later push on ids does not update them.