JAVASCRIPT / CHAPTER 08

Transform collections without surprises

Intermediate

Use array operations while tracking object identity.

By the end of this chapter

  • Select map, filter, or reduce for a result shape
  • Preserve caller-owned arrays
  • Recognize shallow copies

The idea

Array methods communicate the shape of a transformation. Use map to produce one output per input, filter to retain selected inputs, and reduce to combine inputs into a single accumulated result. Give reduce an explicit initial value when empty arrays are allowed. A chain is useful when each step has a clear purpose, not simply because fewer lines appear elegant.

Creating a new array does not automatically create new objects inside it. Array spread and slice copy the outer collection, leaving nested objects shared. When an update must preserve its input, create a replacement object for the changed item as well. Also distinguish nonmutating transformations from sort, reverse, and splice, which change their receiver. Tests should inspect the original input after the operation.

JavaScript example
const tasks = [{id: 1, done: false}, {id: 2, done: false}];
const updated = tasks.map(t => t.id === 2 ? {...t, done: true} : t);
console.log(tasks[1].done);
console.log(updated[1].done);
Result
false
true

The second item is replaced with a new object. Unchanged items may remain shared because the code does not modify them.

Try it yourself

Return a new array of active users sorted by numeric score without changing the input array.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

Open JavaScript coding challenges

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which operation produces one numeric length per input string?