Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

287
Vistas
Passing parameters to reduce function

I have read this article, but I don't seem to understand JavaScript's reduce syntax correctly. How can I pass additional parameters to custom reducer function?

Calling reducer function.

data = Object.values(data.reduce(reducer, {}));

Reducer function example.

const reducer = (acc, cur) => {
if (somethingIsTrue) {
return acc;
}
};

Right now it is working like it should, but let's say that I'm calling reducer function and I want to pass simple variable that contains "Hello World" in away that function doesn't see it as an argument. How can I achieve this?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can do function composition to "build up" something called an higher order function. Basically the idea is to create a function that returns a "child function", which will have access to the parent function's variables.

// Parent function (getReducer)
function getReducer(stringToAppend) {
    
    // Child function (reducer)
    function reducer(acc, curr) {
        // Child function has access to parent's variables (in this case stringToAppend)
        acc[curr] = stringToAppend + curr
        return acc
    }
    
    return reducer
}

const data = [0,1,2,3,4,5,6,7,8,9]
const result = data.reduce(getReducer("Hello World "), {})
console.log('result :>> ', result);

In console:

result :>>  {
  '0': 'Hello World 0',
  '1': 'Hello World 1',
  '2': 'Hello World 2',
  '3': 'Hello World 3',
  '4': 'Hello World 4',
  '5': 'Hello World 5',
  '6': 'Hello World 6',
  '7': 'Hello World 7',
  '8': 'Hello World 8',
  '9': 'Hello World 9'
}

I used the function syntax as I found it more verbose and explicit for explaining this. You could of course utilize arrow functions. Using arrow syntax the function could look as simple as:

function getReducer (stringToAppend) {
    return (acc, curr) => {
        acc[curr] = stringToAppend + curr
        return acc
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda