Loading lessons...
Array Search
Array Search
Arrays have several methods for finding items.
indexOf
Finds the first position of a value, or -1:
["a", "b", "c"].indexOf("b"); // 1
["a", "b"].indexOf("z"); // -1
includes
Checks if a value exists, returning true/false:
["a", "b"].includes("a"); // true
find and findIndex
findreturns the first matching item.findIndexreturns the index of the first matching item.
[10, 20, 30].find(n => n > 15); // 20
[10, 20, 30].findIndex(n => n > 15); // 1
lastIndexOf
Finds the last position of a value:
[1, 2, 1].lastIndexOf(1); // 2
indexOf vs includes
- Use
includeswhen you only need to know "does it exist?". - Use
indexOfwhen you need the position.
TL;DR
- indexOf finds the first position or -1.
- includes checks existence.
- find returns the item; findIndex the index.
- lastIndexOf finds the last position.