Emmanuel Akinfulubi

JavaScriptArray

find vs findIndex vs filter in JavaScript

Beginner · 3 min read

Real data is usually a list of records: products, users, orders, bus fares. You rarely look for an exact value in a list like that. Instead you ask a question about each record, like "which fare costs more than 500?". JavaScript has three methods for this, and they look alike: find, findIndex and filter.

In this tutorial you will use all three on the same list, learn what each one hands back, including when nothing matches, and count how much work each one does. You should know arrays, objects and arrow functions.

Predicates

All three methods take a predicate: a small function that receives one item and returns true or false. "Does this item match?"

JavaScript

const isDear = (f) => f.price > 500;
console.log(isDear({ route: 'Ikeja', price: 900 })); // true
console.log(isDear({ route: 'Yaba', price: 450 }));  // false

The method calls your predicate on the items, one at a time, from the start of the array. What it does with the answers is what makes the three methods different.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

10 find, findIndex and filter

easy

From a list of records, get the first match, the position of the first match, and every match. Then show which of the three stops early.

Stuck? Three hints, smallest first
  1. 1. find returns the element, findIndex returns its position, filter returns an array.
  2. 2. Their miss values all differ: undefined, -1, and an empty array.
  3. 3. Count how many times the predicate runs to see which methods stop at the first hit.

Step 1: the data

Step 1

const fares = [
  { route: 'Yaba', price: 450 },
  { route: 'Ikeja', price: 900 },
  { route: 'Ojota', price: 450 },
];

Three fares. One is dear (Ikeja, 900). Two are cheap (Yaba and Ojota, both 450). We will reuse this list in every step.

Step 2: find gives you the item

find returns the first item the predicate says yes to.

Step 2

const fares = [
  { route: 'Yaba', price: 450 },
  { route: 'Ikeja', price: 900 },
  { route: 'Ojota', price: 450 },
];
const firstDear = fares.find((f) => f.price > 500);
console.log(firstDear.route);        // 'Ikeja'
console.log(firstDear === fares[1]); // true

The last line matters. find gives back the object that is in the array, not a copy. If you change firstDear.price, the fare inside fares changes too.

Step 3: findIndex gives you the position

findIndex runs the same search, but returns where the match is.

Step 3

const fares = [
  { route: 'Yaba', price: 450 },
  { route: 'Ikeja', price: 900 },
  { route: 'Ojota', price: 450 },
];
console.log(fares.findIndex((f) => f.price > 500)); // 1

You want the position when you are about to replace or remove that item, for example with splice or with.

Step 4: filter gives you all of them

filter returns a new array of every item that passes.

Step 4

const fares = [
  { route: 'Yaba', price: 450 },
  { route: 'Ikeja', price: 900 },
  { route: 'Ojota', price: 450 },
];
const allCheap = fares.filter((f) => f.price === 450);
console.log(allCheap.map((f) => f.route)); // [ 'Yaba', 'Ojota' ]

map here just pulls out the route names so the output is short.

Step 5: when nothing matches

Each method has its own way of saying "nothing found":

Step 5

const fares = [
  { route: 'Yaba', price: 450 },
  { route: 'Ikeja', price: 900 },
  { route: 'Ojota', price: 450 },
];
console.log(fares.find((f) => f.price > 1e6));      // undefined
console.log(fares.findIndex((f) => f.price > 1e6)); // -1
console.log(fares.filter((f) => f.price > 1e6));    // []

1e6 is a short way to write 1,000,000. Remember these three: undefined, -1 and an empty array. Before you use the result of find, check it isn't undefined, or firstDear.route will throw a TypeError.

Step 6: who stops early?

Count how many times the predicate runs, by adding one to a counter inside it.

Step 6

const fares = [
  { route: 'Yaba', price: 450 },
  { route: 'Ikeja', price: 900 },
  { route: 'Ojota', price: 450 },
];
let findCalls = 0;
fares.find((f) => { findCalls++; return f.price > 500; });
let filterCalls = 0;
fares.filter((f) => { filterCalls++; return f.price === 450; });
console.log(findCalls);   // 2
console.log(filterCalls); // 3

find checked Yaba (no), then Ikeja (yes), and stopped. It never looked at Ojota. findIndex stops in the same way. filter can't stop early, because it has to collect every match, so it always visits every item.

That is why filter(...)[0] is a poor stand-in for find(...). It gives the same first item, but it walks the whole list to do it.

The full solution

The panel runs all three methods on the fares, shows their three "not found" values, and prints how many times each predicate ran. Press Run to see the output.

The answer

const fares = [
  { route: 'Yaba', price: 450 },
  { route: 'Ikeja', price: 900 },
  { route: 'Ojota', price: 450 },
];

let findCalls = 0;
const firstDear = fares.find((f) => { findCalls++; return f.price > 500; });

let filterCalls = 0;
const allCheap = fares.filter((f) => { filterCalls++; return f.price === 450; });

console.log('find      :', firstDear);
console.log('findIndex :', fares.findIndex((f) => f.price > 500));
console.log('filter    :', allCheap.map((f) => f.route));
console.log('--- the miss values are all different ---');
console.log('find    misses ->', fares.find((f) => f.price > 1e6));
console.log('findIndex misses ->', fares.findIndex((f) => f.price > 1e6));
console.log('filter  misses ->', fares.filter((f) => f.price > 1e6));
console.log('predicate calls: find', findCalls, 'of 3, filter', filterCalls, 'of 3');

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('find returns the element itself', firstDear.route, 'Ikeja');
test('findIndex returns its position', fares.findIndex((f) => f.price > 500), 1);
test('filter returns every match', allCheap.map((f) => f.route), ['Yaba', 'Ojota']);
test('find gives undefined when nothing matches', fares.find((f) => f.price > 1e6), undefined);
test('findIndex gives -1', fares.findIndex((f) => f.price > 1e6), -1);
test('filter gives an empty array', fares.filter((f) => f.price > 1e6), []);
test('find stopped at the second element', findCalls, 2);
test('filter had to visit all three', filterCalls, 3);
test('find returns the element, so it is the same object', firstDear === fares[1], true);

Three methods, one predicate, three different answers to "what did you find". Reach for find when you want the thing, findIndex when you need to splice or replace it, and filter when you want all of them.

The call counts are the practical difference: find and findIndex stop at the first hit, filter always walks the whole array. So filter(...)[0] is not just wordier than find(...), it does more work — and on an empty result it gives undefined by indexing rather than by design.

The last assertion is worth noticing: find hands back the original object, not a copy, so mutating it mutates the array's element.

Common mistakes

  • Expecting filter to return one item. It always returns an array, even for a single match. Use find if you want the item.
  • Using the result of find without a check. A miss is undefined, and undefined.route throws. Check first, or use ?..
  • Changing the found object by accident. find returns the real item, not a copy. Copy it first ({ ...item }) if you only want to edit your own version.

Try it yourself

  1. Find the first fare under 500 and print its route.
  2. Use findIndex and with to make a new list where the Ikeja fare costs 800.
  3. Use filter and map to get the routes of every fare that costs 450, in one chain.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.