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

102
Vistas
Creating an array of functions returning their index without loops

I would like to create a function returning an array of functions. When any function from the array is called, the result must be the index of this function in the array. The task and challenge are to create this function without for-loops. I was moving this way, however, the code did not work as I expected:

const createArrayOfFunctions = number => {

  const functionsArray = new Array(number).fill();

  return functionsArray.map(element => function() {

    return functionsArray.indexOf(element);

  });

};

I expected:

const testArray = createArrayOfFunctions(7);
testArray[2](); // 2;

Is there any way to have the goal achieved without using for-loops. I need it for a study project.

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

0

First, you use new Array(number).fill(), which makes an array of undefined. So, when you call testArray(2)(), your element inside your return function is also undefined. then you tried to find the index of undefined, it returns 0. The reason it returns 0 is because your functionsArray is an array of 7 undefined in your case, then Array.indexOf will return the first match, and since functionArray[0] is undefined, that's why it always return 0 no matter which function you call within your functionArray. Make sense?

I made a little change of your code, try this. It should work as you would expect. I didn't use Array.indexOf or any other array methods just because you only want the index, why not consider using the index instead?

If you insist that you want to use Array.indexOf to solve your problem, you will have to use a forloop inside createArrayOfFunctions to create your functionsArray with different elements(e.g. 0,1,2,3,4...7), because new Array(number).fill() creates array of undefined, and even if you do Array(number).fill(number), you still just create an array of 7s in your case, so that is exactly the same thing as an array of 7 undefined in your case. So your method won't work. Since you mentioned no forloop, that's why I provided the method using index as described above.

Also I would recommend you to add some logic or create a separate function to make sure no one can call the testArray out of bound, for example, if you create 7 array functions, you don't want people to be able to call testArray[8]. I hope this helps. let me know if you have any confusion.

const createArrayOfFunctions = (number) => {
  functionsArray = new Array(number).fill(0);
  return functionsArray.map((element, index) => {
    return () => {          
      return index;
    };
  });
};

const testArray = createArrayOfFunctions(7);
console.log(testArray[2]()); // 2;
console.log(testArray[3]()); // 2;
console.log(testArray[1]()); // 2;

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can achieve your goal by using Array.from like this:

const createArrayOfFunctions = length => Array.from({length}, (v, i)=> ()=> i);

const arrayOfFunctions = createArrayOfFunctions(10);
console.log(arrayOfFunctions[0]())
console.log(arrayOfFunctions[9]()) // last item would be 9

about 4 years ago · Juan Pablo Isaza Denunciar

0

First of all, I suggest you change new Array().fill() to just [].

We are able to recreate a for loop using a while loop.

let x = 0
while (x < 5) {
console.log(`five times`)
x++
}

Therefore, I suggest you do this:

function createarray() {
let arrayfunc = []
let i = 0
while(i<10) {arrayfunc.push(new Function(‘console.log(\‘ + i + \‘)\‘))}
return arrayfunc
}
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