AI Hints
Home›JavaScript Tutorial›Searching and Sorting
JavaScript · Lesson 46 of 138

Finding Things

IndexOf, includes, find.

⏱ 2 min read▶ Video at 55:48🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Is milk on the shopping list? Where is it? Which is the first price over ten dollars? Arrays have methods for all of these questions.

Finding Things
From the video: Finding Things
  • Is it there?
  • Where is it?
  • Which one matches?

Search methods

Includes answers yes or no. Index of gives the position, or minus one if it's not there. Find takes a callback, and returns the first item where the callback returns true. Find index returns that item's position instead. Run it.

app.jsjavascript
const list = ["eggs", "milk", "bread"];
console.log(list.includes("milk"), list.indexOf("milk"), list.indexOf("jam"));

const prices = [3, 8, 15, 22];
console.log(prices.find(p => p > 10));
console.log(prices.findIndex(p => p > 10));
console.log(prices.some(p => p > 20), prices.every(p => p > 1));
Output
true 1 -1
15
2
true true

Some and every

Two more handy methods. Some asks, does at least one item pass the test? Every asks, do all of them pass? Both stop as soon as they know the answer. And remember, index of returns minus one when there's no match, so always check for that.

keyvalue
includes(x)true or false
indexOf(x)position or −1
find(fn)first match
some / everyany? all?

Finding objects

Find and find index are most useful with arrays of objects. Find gives back the whole object, so we can read its other properties. Find index gives its position. And if nothing matches, find gives undefined, and find index gives minus one. Run it.

app.jsjavascript
const users = [
  { id: 1, name: "Ana" },
  { id: 2, name: "Ben" },
  { id: 3, name: "Cara" },
];

console.log(users.find(u => u.id === 2).name);
console.log(users.findIndex(u => u.name === "Cara"));
console.log(users.find(u => u.id === 9), users.findIndex(u => u.id === 9));
Output
Ben
2
undefined -1

Summary

Includes and index of search for a value, and find, some, and every search with a test. Next, copying and changing parts of an array.

Key takeaways
  • includes / indexOf
  • find / findIndex
  • some / every
Next up: slice and splice — copies and changes