Arrays and object transformations
Arrays store ordered collections; objects group values by named properties. Backend code frequently transforms arrays of records into lists, summaries or response data. filter() selects elements, map() transforms elements, and reduce() accumulates a result.
Local practice: The proposed teaching runtime is Node.js 26.13.1 LTS. These original offline examples were executed on Node.js 22.16.0 (Linux x64); execution on the proposed baseline and in ByteMind is not yet verified. No npm dependencies are required. Use a fresh practice directory. Code blocks are static, not a browser-based Node runner.
Return available book titles
const books = [ { title: "River Maps", available: true }, { title: "Night Atlas", available: false }, { title: "City Walks", available: true }];const titles = books.filter(book => book.available).map(book => book.title);console.log(JSON.stringify(titles));In the directory containing the files above, run:
node main.mjsExpected standard output:
["River Maps","City Walks"]Expected exit status: 0.
How it works
Each method receives a callback function called for elements of the array. In the first example, book => book.available means return the boolean property for the current book; filter includes records whose callback result is truthy. The map callback returns only the title. In the second example, reduce starts from 0, adds each quantity, and returns the final sum. A new array is not a deep copy: object elements may still refer to the original objects. The shown functions do not mutate their inputs.
Sum quantities with an initial value
function countItems(items) { return items.reduce((sum, item) => sum + item.quantity, 0);}console.log(countItems([{quantity: 2}, {quantity: 5}]));console.log(countItems([]));In the directory containing the files above, run:
node main.mjsExpected standard output:
70Expected exit status: 0.
Common mistake
An omitted initial accumulator can make reduce() throw on an empty array, and it can change which value is used first. For numeric totals start at 0. Filtering an array of objects does not clone each object; mutating a selected object may change the original record.
Try it yourself
Given three fictional items with quantity and available fields, select available items and sum their quantities. Test an empty array and a list with no available items. Expect zero in both edge cases.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Arrays and object transformations — knowledge check
Check your understanding of arrays and object transformations.
Which method selects matching records?
Why is 0 supplied to reduce?
Does filtering an array of objects deep-clone the objects?