Introducción a JavaScript
¿Por qué aprender JavaScript?
¡Hola Mundo! en Mac
¡Hola Mundo! en Windows
Anatomía de una variable
Tipos de datos en JavaScript
Creación de strings
Operadores aritméticos
Conversión de tipos: Type Casting y Coerción
Conversión de tipos explícita e implícita
Estructuras de Control y Lógica
Operadores de comparación
Operadores lógicos
Ejecución condicional: if
Ejercicio: Adivina el número
Ejecución condicional: switch
Loop: for
Loop: for of
Loop: for in
Loop: while
Loop: do while
Funciones y This
Anatomía de una función
Funciones vs Métodos
Funciones puras e impuras
Arrow function y enlace léxico
Contextos de ejecución y scope chain
¿Qué es Closure?
Preguntas a Desarrolladores Senior: ¿Por qué aprender Desarrollo Web?
Manipulación de Arrays
Introducción a Arrays
Mutabilidad e inmutabilidad de Arrays
Modificación básica del final con push( ), pop( )
Iteración con map( ) y forEach( )
Filtrado y reducción con filter( ) y reduce( )
Búsqueda de elementos con find( ) y findIndex( )
Crear copias con slice( )
Spread operator: casos de uso
Programación Orientada a Objetos
Anatomía de un Objeto
Trabajando con objetos en JavaScript
Función constructora
¿Qué es una clase?
Prototipos y herencias
Herencia en la práctica
Prototipos en la práctica
this en JavaScript
Proyecto: Crea una red social
Proyecto: Crea una red social parte 2
Asincronía en JavaScript
¿Cómo funciona el JavaScript Engine?
Promesas en JavaScript
Usando Async y await en JavaScript
For await of
¿Cómo funciona la web?
¿Cómo funciona HTTP?
Método GET en JavaScript
Método POST en JavaScript
Método DELETE en JavaScript
Importancia del id en el método DELETE
ECMAScript 6 y tus siguientes pasos
You don't have access to this class
Keep learning! Join and start boosting your career
Welcome programming enthusiasts! Today we will explore two fundamental methods of arrays in JavaScript: Filter
and Reduce
. Both are powerful tools that do not alter the original array, allowing you to filter and reduce data efficiently. They enrich list management by providing flexibility in dealing with complex data, making them indispensable in any developer's arsenal.
The Filter
method creates a new array with all the elements that pass the condition implemented in the provided test function. Imagine having an array of numbers and wanting only those that meet a certain condition, such as being greater than a specific number.
Let's see a practical and simple example:
let numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10];let evenNumbers = numbers.filter(number => number % 2 === 0);console.log(evenNumbers); // Output: [2, 4, 6, 8, 10].
In this code block, filter
receives an arrow function that evaluates whether each number in the array is even (i.e., the modulus of 2 is zero), returning a new array with these even numbers.
Unlike Filter
, the Reduce
method takes an array and reduces it to a single value by applying a function that runs on each value in the array, from left to right. A classic use of reduce
is to sum all the elements of an array.
Let's look at how reduce
works when adding numbers:
const numbersReduce = [1, 2, 3, 4, 5];const sum = numbersReduce.reduce((accumulator, currentValue) => accumulator + currentValue, 0);console.log(sum); // Output: 15.
Here, reduce
accumulates each array value in the accumulator
starting from zero(initialValue
) until the total sum of the array is achieved.
Reduce
is versatile and can be used for more complex cases, such as counting the frequency of word occurrences in an array. This transforms a potentially complex problem into an elegant and concise solution.
Let's see how to count how many times each word in an array is repeated:
const words = ['apple', 'banana', 'hello', 'bye', 'banana', 'bye', 'bye ', 'bye'];const wordFrequency = words.reduce((accumulator, currentValue) => { accumulator[currentValue] = (accumulator[currentValue] || 0) + 1; return accumulator;}, {});
console.log(wordFrequency); // Output: { apple: 1, banana: 2, hello: 1, bye: 3 }
In this example, we use an object as an accumulator where each time we find a word, we increment its count in the object, thus obtaining the frequency of each word.
Delving into the world of Filter
and Reduce
will give you valuable skills to manipulate arrays efficiently, making your lines of code more streamlined and powerful, so go ahead and keep exploring and experimenting with these methods!
Contributions 26
Questions 0
Want to see more contributions, questions and answers from the community?