Home › Learn › JavaScript › Arrays

map and filter

Lesson 18 of 40. Transform every item, or keep some of them.

items.map(fn) returns a new array with fn applied to every item: [1, 2, 3].map(n => n * 2) is [2, 4, 6]. items.filter(fn) returns a new array with only the items for which fn returned something truthy. Neither changes the original, and both take an arrow function, the short function syntax (x) => expression.

They chain naturally: words.filter(w => w.length > 3).map(w => w.toUpperCase()). Prefer them to hand-written loops when the intent is "transform" or "keep"; the loop is still right for anything more involved.

const words = ["hi", "hello", "hey"];
const longUpper = words.filter((w) => w.length > 2).map((w) => w.toUpperCase());
console.log(longUpper);   // ["HELLO", "HEY"]

Your task

Using map and filter, write squares(nums) returning each number squared, evens(nums) returning only the even numbers, and longWords(words, n) returning the words longer than n characters in upper case.

Hint 1

return nums.map((n) => n * n);

Hint 2

return words.filter((w) => w.length > n).map((w) => w.toUpperCase());

Show the solution
function squares(nums) {
  return nums.map((n) => n * n);
}

function evens(nums) {
  return nums.filter((n) => n % 2 === 0);
}

function longWords(words, n) {
  return words.filter((w) => w.length > n).map((w) => w.toUpperCase());
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.