JS Array Search
Five methods locate items in an array. Pick by whether you want the item, the index, or just a boolean.
| Method | Returns | Use it for |
|---|---|---|
indexOf(value) | Index or -1 | Exact value match. |
lastIndexOf(value) | Index or -1 | Same, from the right. |
includes(value) | Boolean | "Is X in the list?" |
find(fn) | First matching item, or undefined | Find by predicate. |
findIndex(fn) | Index of first match, or -1 | Need the position too. |
findLast(fn) / findLastIndex(fn) | Same, from the right | Newest matching record. |
some(fn) | Boolean — any pass | "Are any X?" |
every(fn) | Boolean — all pass | "Are all X?" |
Examples
JS
const users = [
{ id: 1, name: "Ada", admin: true },
{ id: 2, name: "Grace", admin: false },
{ id: 3, name: "Linus", admin: true },
];
users.includes("Ada"); // false — wrong type, looking for object
users.find(u => u.name === "Ada"); // { id: 1, name: "Ada", admin: true }
users.findIndex(u => u.id === 2); // 1
users.some(u => u.admin); // true
users.every(u => u.admin); // false
users.findLast(u => u.admin); // { id: 3, name: "Linus", admin: true }
Note:
indexOf and includes both use ===. They won't find objects by content — only by reference. Reach for find with a predicate when matching object fields.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Array Search!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Find the first user whose id equals 2.
const found = users.
(u => u.id === 2);
Four letters.
Discussion
Loading…