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.
You will practise
- Use an array method instead of mutation
- Understand what filter copies
Examples
- [{ 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
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
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
const sports = [{ name: 'cricket' }, { name: 'football' }];
assert.ok(filterCricket(sports)[0] === sports[0], 'filter does not copy the elements');Related questions
Source: Full Stack / JS — task card — The task and reference solution come from the card; the tests were written from its description.