Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda