Array methods · Métodos de Matriz
Array methods
.map(fn)makes a new array by transforming each item..filter(fn)makes a new array of only the items wherefnreturnstrue..forEach(fn)runsfnfor each item, making no new array.
Métodos de Array
.map(fn)cria um novo array transformando cada item..filter(fn)cria um novo array apenas com os itens ondefnretornatrue..forEach(fn)executafnpara cada item, sem criar um novo array.
let nums = [1, 2, 3];
let doubled = nums.map((n) => n * 2);
console.log(doubled); // → [2,4,6]
Filtering keeps some items
.filterkeeps each item for which the test returnstrue.
Filtragem mantém alguns itens
.filtermantém cada item para o qual o teste retornatrue.
let nums = [3, 7, 2, 9];
let big = nums.filter((n) => n > 4);
console.log(big); // → [7,9]
Watch out
.mapand.filterreturn a new array — the original is untouched.- You hand each one an arrow function that says what to do with one item.
Atenção
.mape.filterretornam um novo array — o original permanece intacto.- Você passa para cada um uma arrow function que diz o que fazer com um item.
Common mistakes
mapandfilterreturn a NEW array — they do not change the original.forEachjust loops and returns nothing.
Erros comuns
mapefilterretornam UM NOVO array — eles não mudam o original.forEachapenas faz loop e retorna nada.
Now you try
- Use
.map,.filteror.forEach. - Press Check answer to test it.
Agora você tenta
- Use
.map,.filterou.forEach. - Pressione Check answer para testá-lo.
Use .map to double every number in [1, 2, 3] and store the new array in result (it should be [2, 4, 6]). · Use .map para dobrar cada número em [1, 2, 3] e armazene a nova matriz em result (deveria ser [2, 4, 6]).
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Use .filter to keep only the numbers greater than 4 from [3, 7, 2, 9, 1], in a variable big (it should be [7, 9]). · Use .filter para manter apenas os números maiores que 4 de [3, 7, 2, 9, 1], em uma variável big (deveria ser [7, 9]).
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Use .forEach to add every number in [4, 8, 15] to · até total (it should end up 27). · Use .forEach para somar todos os números em [4, 8, 15] a total (deve terminar sendo 27).
Click Run to see the output here. · Clique em Executar para ver a saída aqui.