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

116
Vistas
Create two dimensional array from two arrays

I've got these two arrays and I need to obtain c. I managed to obtain a solution with two fors and conditionals, but I'm sure something better than O^2 can be obtained with JS.

a = [3, 2, 1, 3]
b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

c = [['a', 'b', 'c'], ['d', 'e'], ['f'], ['g', 'h', 'i']]
about 4 years ago · Santiago Gelvez
3 Respuestas
Responde la pregunta

0

For fun purpose I wrote it in a coincisive way, hope you like it:

const a = [3, 2, 1, 3];
const b = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
const bClone = [...b];

const array = a.map((num, index) =>
  Array.from({ length: num }, () => bClone.shift())
);

console.log(array);

Of course controls should be added, thanks

about 4 years ago · Santiago Gelvez Denunciar

0

I don't have that much good background in algorithms but I think this is better than two fors:

let a = [3, 2, 1, 3]
,b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

let head = 0

let result = a.map((e) => {
      let subArr = b.slice(head,head+e)   
      head +=e
      return subArr
  })
  
 console.log(result)

about 4 years ago · Santiago Gelvez Denunciar

0

One possibility is to combine map with splice, taking care not to mutate the original array:

const a = [3, 2, 1, 3];
const b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];

function slices(sizes, arr){
  const clonedArr = [].concat(arr);     // clone array to prevent mutation 
  return sizes.map(size => clonedArr.splice(0,size));
}

console.log(slices(a,b));     // [['a', 'b', 'c'], ['d', 'e'], ['f'], ['g', 'h', 'i']]

Alternatively, avoiding mutation altogether, you could use slice with a slightly convoluted reduce:

const slicesByReduce = (sizes, arr) => sizes
  .reduce(({start, acc}, size) => ({
    start: start + size,
    acc: [...acc, arr.slice(start, start + size)]
  }),{
    start: 0,
    acc: []
  }).acc;

console.log(slicesByReduce(a,b));     // [['a', 'b', 'c'], ['d', 'e'], ['f'], ['g', 'h', 'i']]
about 4 years ago · Santiago Gelvez 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