Skip to content
Jobless Busters
Runs testsBasic

Filtering sports

Write filterCricket(sports), which returns a new array of the items whose name is 'cricket', without changing the input array.

The result holds references to the same objects — filter doesn't make a deep copy. I take the field name and comparison rules from the task statement.

  • Use an array method instead of mutation
  • Understand what filter copies
  • [{ name: 'cricket' }, { name: 'football' }, { name: 'cricket' }]→ [{ name: 'cricket' }, { name: 'cricket' }]
The 3 tests

Tests written from the card: a new array, no mutation of the input, the same object references.

returns only cricket

JavaScript
const sports = [{ name: 'cricket' }, { name: 'football' }, { name: 'cricket' }];
assert.deepEqual(filterCricket(sports), [{ name: 'cricket' }, { name: 'cricket' }]);

doesn't change the input and returns a new array

JavaScript
const sports = [{ name: 'cricket' }, { name: 'football' }];
const result = filterCricket(sports);
assert.ok(Array.isArray(result) && result !== sports, 'the result should be a new array');
assert.deepEqual(sports, [{ name: 'cricket' }, { name: 'football' }]);

holds references to the same objects

JavaScript
const sports = [{ name: 'cricket' }, { name: 'football' }];
assert.ok(filterCricket(sports)[0] === sports[0], 'filter does not copy the elements');

Source: Full Stack / JS — task card — The task and reference solution come from the card; the tests were written from its description.

JavaScript · runs in a Web Worker in your browser

Tab indents · Esc, then Tab, leaves the editor · ⌘/Ctrl + Enter runs the tests · Your code is saved in this browser.

Run the tests to check your solution. 3 predefined tests.

Stuck? Hints go from gentle to specific.

Give it a real try first — the solution is most useful after you've struggled a bit.