Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Array-metoder «map», «filter» | Seksjon
Javascript-Grunnleggende

bookArray-metoder «map», «filter»

Sveip for å vise menyen

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.

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 13

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 1. Kapittel 13
some-alt