Skip to content

Instantly share code, notes, and snippets.

@jairoFernandez
Created December 19, 2020 21:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jairoFernandez/6f0d5c592701408c05c4ee624172879a to your computer and use it in GitHub Desktop.
Save jairoFernandez/6f0d5c592701408c05c4ee624172879a to your computer and use it in GitHub Desktop.
Reducer examples
console.clear()
// const reducer = (acumulador, valorActual) => nuevoAcumulador
// valor inicial
// const reducido = [1, 2, 3].reduce((acc, el) => acc + el, 0)
// console.log(reducido) // 6
const numeros = [1, 2, 3, 4, 5]
const resultado = numeros.reduce((acc, el) => acc + el, 0)
// console.log(resultado)
const mascotas = [
{ nombre: 'Pelusa', edad: 12, tipo: 'gato' },
{ nombre: 'Puchini', edad: 12, tipo: 'perro' },
{ nombre: 'Pulga', edad: 10, tipo: 'perro' },
{ nombre: 'Chanchito feliz', edad: 3, tipo: 'perro' },
]
const indexed = mascotas.reduce((acc, el) => ({
...acc,
[el.nombre]: el
}), {});
// console.log(indexed['Chanchito feliz'])
const anidado = [1, [2, 3], 4, [5]]; // => [1,2,3,4,5]
const plano = anidado.reduce((acc, el) => acc.concat(el), []);
console.log(plano)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment