iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Array Search

Five methods locate items in an array. Pick by whether you want the item, the index, or just a boolean.

MethodReturnsUse it for
indexOf(value)Index or -1Exact value match.
lastIndexOf(value)Index or -1Same, from the right.
includes(value)Boolean"Is X in the list?"
find(fn)First matching item, or undefinedFind by predicate.
findIndex(fn)Index of first match, or -1Need the position too.
findLast(fn) / findLastIndex(fn)Same, from the rightNewest 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);

Test yourself

Q1. Find the first user with id === 2 using…
Q2. Test if at least one item passes a predicate with…
Q3. `arr.includes(obj)` searches by…

Discussion

Loading…