Javascript Fundamentals · Array Methods

Keep the matching elements

filter

Keep the matching elements

Your stock list holds everything you sell, but today you only want the items that are in stock. You need a shorter list — the matching entries in order, nothing else — and the full list must stay as it was.

That selection is filter. It builds a new array containing only the elements that pass a test. Where map keeps every element and changes it, filter keeps some elements and changes nothing.

const items = [
  { name: 'Pen', inStock: true },
  { name: 'Ruler', inStock: false },
];

const available = items.filter((item) => item.inStock);
// [{ name: 'Pen', inStock: true }]

filter hands the callback each element (and its index) and keeps the element whenever the callback returns a truthy value. The kept elements are the same references, in their original order, inside a brand-new array.

The pitfall: the callback must return a boolean test, not a transformed value. Returning an object (for example item.name) is always truthy, so nothing ever gets dropped — reach for map when you want to change elements and filter when you want to select them.

Export availableItems from index.js. Given a list of items, return a new array holding only the items where inStock is true.

Challenge

Your stock list holds everything you sell, but you only want what is available today. Walking it to pick out the in-stock items by hand is fiddly, and the full list still needs to stay intact. Export an availableItems function from index.js to select them.

availableItems takes an array of items — each an object with a name and an inStock boolean — and returns a new array holding only the items where inStock is true, in their original order. The source array must not be changed.

index.js
export function availableItems(items) {
  return [...items];
}

export function render(mount) {
  const items = [
    { name: 'Pen', inStock: true },
    { name: 'Ruler', inStock: false },
    { name: 'Notebook', inStock: true },
  ];

  const available = availableItems(items);

  mount.textContent = `Available: ${available.map((item) => item.name).join(', ')}`;
}

No test run yet

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