Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Array Methods `map`, `filter` | Section
JavaScript Basics

bookArray Methods `map`, `filter`

Swipe to show menu

Arrays often need to be transformed or filtered to create new versions based on existing data. JavaScript provides higher-order array methods like map and filter that make these tasks concise and readable.

These methods help you avoid manual loops and let you focus on what you want to achieve with your data, rather than how to do it step by step. Using higher-order methods leads to code that is easier to maintain, understand, and reuse.

123456
// Using map to create a new array with doubled values const numbers = [1, 2, 3, 4]; const doubled = numbers.map(function(num) { return num * 2; }); console.log(doubled); // [2, 4, 6, 8]
copy

When you use map, JavaScript creates a new array by calling your function once for each element in the original array. The value returned by your function becomes the new value in the resulting array, and the original array is not changed.

123456
// Using filter to create a new array with only even numbers const numbers = [1, 2, 3, 4, 5, 6]; const evens = numbers.filter(function(num) { return num % 2 === 0; }); console.log(evens); // [2, 4, 6]
copy

With filter, your function should return true to keep an element or false to exclude it. Only the elements that pass your test function are included in the new array, while the original array remains unchanged.

Both map and filter loop through the array internally, so you do not need to write a manual loopβ€”they take care of iterating and building the new array for you.

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 1. ChapterΒ 13

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

SectionΒ 1. ChapterΒ 13
some-alt