DEV Community

João Costa
João Costa

Posted on

3 2

Map, Filter e Reduce em JavaScript

O que são map, filter e reduce?

São funções no protótipo de um array JavaScript e podem ser usadas para operações baseadas em iterações em uma coleção de itens armazenados nesse array.

Map

Map é uma função que percorre o array e retorna um novo.

const numbers= [1, 2, 3, 4, 5];

const newArr= numbers.map(item => {
  return item * 2;
});
Enter fullscreen mode Exit fullscreen mode

Então como map gera um novo array numbers retorna o mesmo array, enquanto newArr retorna outro array com os valores duplicados.

Filter

Filter é a função que retorna um array filtrado pelas condições que fornecemos.

const numbers = [1, 2, 3, 4, 5];

const newArr = numbers.filter(item => {
  return item % 2 === 0;
});
Enter fullscreen mode Exit fullscreen mode

Pela condição que colocamos acima a função só irá retornar os números par.

Reduce

Reduce é a função que percorre o array e reduz ele a um único valor.

const numbers = [1, 2, 3, 4, 5];

const newArr = numbers.reduce((acc, item) => {
  acc = acc + item;
  return acc;
});
Enter fullscreen mode Exit fullscreen mode

Reduce recebe dois argumentos o acumulador e o item atual. Cada item é adicionado ao acumulador antes que o acumulador seja retornado para a próxima passagem. Retornando em um valor de 15.

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay