Arrays and objects
Organize items by position and model a record with named properties.
Read an ordered sequence
Arrays hold values in order. Index 0 is the first item. for...of visits the values in the array, while .map() builds a new array by transforming each item.
How it works
In a list of book objects, an array index selects a book and a property name selects one detail within it. For example, books[0].title chooses the first book and then reads its title. Check that both the item and the field exist when input may be incomplete.
Store fields on an object
An object lets you attach meaning to data with keys such as title and completed. Use dot notation for a literal property name and bracket notation to look up a property stored in a variable. Arrays of objects are a common way to represent lists of records.
Code example
const books = [{ title: "Maps", read: true }, { title: "Stars", read: false }];
const unread = books.filter((book) => !book.read);
console.log(unread.map((book) => book.title).join(", "));Check your understanding
Return an array of titles whose read property is false, in the original order.
See the example and explanation
- Example 1
- Given
Maps (read), Stars (unread), Rivers (unread) - Answer
["Stars", "Rivers"] - Example 2
- Given
Maps (read) - Answer
[]
Filter with book => !book.read, then map with book => book.title. Filtering and mapping preserve the order of retained records.