JavaScript filter() Practice: Arrays of Objects

A product catalogue often contains items that cannot currently be purchased. This exercise separates selecting records from displaying them: first keep available phones, then extract their model names. The same pattern is useful for search results, bookings and task lists.

Before you start: Objects, arrays, arrow functions and booleans.

Your task

Use filter() to keep only phones where inStock is true. Print their model names with map().

Starter code

const phones = [
  { model: "Phone A", inStock: true },
  { model: "Phone B", inStock: false },
  { model: "Phone C", inStock: true },
];

// Keep the available phones, then print their model names.

Expected result

["Phone A", "Phone C"]

Array formatting and quotation marks can differ between consoles. Compare the two model values and their order.

Open this exercise

Loads the starter in the workspace. Save or export existing work first. Return here for hints and the explanation.

Need a hint?

The filter callback should return the inStock value. Use map on the filtered array to select each model.

Show the complete solution and walkthrough
const phones = [
  { model: "Phone A", inStock: true },
  { model: "Phone B", inStock: false },
  { model: "Phone C", inStock: true },
];

// Keep the available phones, then print their model names.
const available = phones.filter(phone => phone.inStock);
console.log(available.map(phone => phone.model));
  1. Read each phone object and check its inStock property. The example uses actual booleans, so true keeps the record and false removes it.
  2. Store the filtered array as available. filter creates a new outer array; it does not remove records from phones. The objects themselves are still shared references.
  3. Use map to turn each available object into a model string. Print the resulting array once, rather than logging each name separately.

A common mistake

Using map to filter produces an array with a result for every original item. Returning false or undefined from map does not remove an element.

Try an edge case

An empty input or an input with no available phones should produce an empty array. The order of matching phones stays the same.

Take it one step further

Add a price property to every phone. Keep phones that are in stock and cost less than 30000, then print their model names.

Read the javascript tool guide