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

117
Vistas
How to create a new array based on the number of sub arrays in js

Here is my first array:

const withSub = [[31, 32, 34, 34], [32, 36], [12], [15, 38]];

Here is my second array:

const arr = ['f', 'b', 'c', 'd'];

The number of arrays in withSub is always equal to the number of arr arrays, while the number of subarrays in withSub may be different.

I want to create a function that generates a new array based on these two arrays in such a way that the number of each element in arr must be equal to the number of subarrays in withArr.

In this example the final array must be:

   ['f', 'f', 'f', 'f', 'b', 'b', 'c', 'd', 'd'];
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

If I understood your question correctly, you can use .flatMap() on your withSub array to map each number within each subarray to their corresponding letter from arr. You can do this by taking the index of the subarray from the flatMap callback, and then use that to obtain the letter from arr when mapping your subarrays.

See example below:

const withSub = [[31, 32, 34, 34], [32, 36], [12], [15, 38]];
const arr = ['f', 'b', 'c', 'd'];

const res = withSub.flatMap((subArr, i) => subArr.map(() => arr[i]));
console.log(res);

about 4 years ago · Juan Pablo Isaza Denunciar

0

you can do something as the following code:

const generate = (numbers, letters) => {
  return numbers.map((nums, i) => {
    return nums.map(num => letters[i])
  }).flat()
}

And then use it with generate(withSub, arr).

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can have an approach with forEach() and spread operator.

forEach() is similar to a forloop with subtle differences.

const awesomeFunction = (withSub , arr) => {
let ans = [];

arr.forEach( (x,index) => {
     let newArr = new Array(withSub[index].length).fill(x);  
     
     ans = [...ans , ...newArr];  
});

return ans; };

const withSub = [[31, 32, 34, 34], [32, 36], [12], [15, 38]];
const arr = ['f', 'b', 'c', 'd'];


console.log(awesomeFunction(withSub,arr));

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