JS Built-ins
← Array62 / 226
ArrayArray.prototype.filterbeginner

Array.prototype.filter() β€” keep even numbers

πŸ“– Usage Example
const nums = [1, 2, 3, 4, 5, 6]
nums.filter(n => n % 2 === 0)  // β†’ [2, 4, 6]

Use filter() with a condition to create a new array containing only matching elements.

Array.prototype.filter()

Array.prototype.filter(callback) returns a new array containing only the elements for which the callback returns a truthy value. The original array is not modified.

Challenge: Implement filterEven(nums) that returns only even numbers from the array.

filterEven([1, 2, 3, 4, 5, 6]) // β†’ [2, 4, 6]
filterEven([1, 3, 5])          // β†’ []
πŸ’‘ Hints (2)
  • β€’ `n % 2 === 0` is the classic even check.
  • β€’ `filter()` never modifies the original array β€” it always returns a new one.