Lesson 12 of 15

Array.filter

Array.filter

filter keeps only the elements that pass a test:

const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens);  // [2, 4, 6]

Like map, filter returns a new array — the original is never modified. This immutability means you can safely filter without worrying about changing the source data.

The function you pass must return true (keep) or false (discard). The result may be shorter than the original.

Chaining

map and filter can be chained:

const result = [1, 2, 3, 4, 5]
    .filter(n => n % 2 !== 0)   // keep odds: [1, 3, 5]
    .map(n => n * n);            // square them: [1, 9, 25]
console.log(result);

Filtering Strings

const words = ["apple", "ant", "banana", "avocado", "cherry"];
const aWords = words.filter(w => w.startsWith("a"));
console.log(aWords);  // ["apple", "ant", "avocado"]

Your Task

Write function positives(numbers) that returns only the positive numbers (greater than 0) from the array.

JavaScript loading...
Loading...
Click "Run" to execute your code.