Javascript Fundamentals · Array Methods

Find the first match

find

Find the first match

Someone hands you a slug and you need the item it points to — title, price, the whole record. Scanning the list and stopping the moment you hit the match is enough; you do not need the rest.

That lookup is find. It returns the first element that passes a test, or undefined when none does. It answers "is there a match, and if so which one?" — not "how many?", and not "give me all of them". Where filter returns an array, find returns a single element (or nothing).

const items = [
  { slug: 'pen', title: 'Pen' },
  { slug: 'notebook', title: 'Notebook' },
];

items.find((item) => item.slug === 'notebook');
// { slug: 'notebook', title: 'Notebook' }

items.find((item) => item.slug === 'marker');
// undefined

find hands the callback each element (and its index) and returns the element as soon as the callback is truthy; every other element is skipped.

The pitfall: no match is not an error — you get undefined, so a lookup that finds nothing looks exactly like a field that was never set. Guard the result before reading a property (item?.title), and remember find returns the element, not its position (that is findIndex).

Export findBySlug from index.js. Given a list of items and a slug, return the first item whose slug matches, or undefined when none does.

Challenge

Someone gives you a slug and you need the item it points to. You could scan the whole list, but the first match is answer enough, and a miss should not throw. Export a findBySlug function from index.js to look it up.

findBySlug takes an array of items — each an object with a slug — and a slug, and returns the first item whose slug matches, or undefined when none does. The search stops at the first match.

index.js
export function findBySlug(items, _slug) {
  return items[0];
}

export function render(mount) {
  const items = [
    { slug: 'pen', title: 'Pen' },
    { slug: 'notebook', title: 'Notebook' },
  ];

  const item = findBySlug(items, 'notebook');

  mount.textContent = item ? item.title : 'Not found';
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.