Technical skill practice

JavaScript Array filter: Select Records Without Cloning Them

filter creates an array of elements whose predicate is truthy. It selects records rather than transforming them into a different shape. The selected objects remain the original references.

The task

Select available workshop supplies and verify what happens when a field on a selected record changes. Keep the source membership and object-content questions separate.

Runnable Node 22 example

const assert = require('node:assert/strict');

const stock = [{id: 'clip', quantity: 4}, {id: 'pad', quantity: 0}, {id: 'pen', quantity: 2}];
const available = stock.filter(item => item.quantity > 0);
assert.deepEqual(available.map(item => item.id), ['clip', 'pen']);
assert.equal(stock.length, 3);
assert.equal(available[0], stock[0]);
available[0].quantity = 3;
assert.equal(stock[0].quantity, 3);
assert.deepEqual(stock.filter(item => item.quantity > 100), []);
console.log(available.map(item => item.id).join(','));

Expected output and explanation

The zero-quantity pad is not selected, so the result has two members while stock still has three. Updating the retained clip record changes the same object visible through stock; filter did not create an independent record copy.

The final check returns an empty array because no quantity exceeds one hundred. That result is a valid selection outcome, not a missing return or a thrown error. A caller can inspect length to decide how to present an empty result.

Output from the example

clip,pen

Pitfall to check

If a callback uses braces, explicitly return the condition. A missing return yields undefined and can filter out every element. Validate quantity types separately if external records may contain text or missing fields.

Questions, answered

Should I use filter to convert each record to an ID?

Use map for transformation. filter preserves selected elements; its predicate decides membership rather than the replacement value.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.