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

135
Visualizações
How to match an array's structure?

I have two arrays which will always have the same number of elements within them.

var array1 = [["John","Barry","Anne"],["Greg"],["Tom"],["Roy","Rye"]]
var array2 = ["Banana","Orange","Apple","Grape","Pineapple","Raspberry","Pear"]

I want array2 to have the same array structure as array1, so it should look like:

var newArray = [["Banana","Orange","Apple"],["Grape"],["Pineapple"],["Raspberry","Pear"]]

I have tried using the length of array1 to firstly create a new array of the right length and then looping over that array to create the nested arrays with the right length. Then using a for loop, pushing array2's element to this new array but I'm having trouble figuring out how to do it.

  var array = new Array(array1.length)
  var arrayLength = array1.map(x => x.length)

  for (var i = 0; i < array.length; i++) {
    array[i] = new Array(arrayLength[i]);
  }
  for (var k = 0; k < array.length; k++) {
    for (var j = 0; j < array[k].length; j++) {
      array[0][k].push(array2[j])
    }
  }

Thanks for any help!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use .map() and .splice() to get the expected result.
If array2 is not allowed to be changed, we need a copy of it -> .slice()

const array1 = [["John", "Barry", "Anne"], ["Greg"], ["Tom"], ["Roy", "Rye"]];
const array2 = ["Banana", "Orange", "Apple", "Grape", "Pineapple", "Raspberry","Pear"];

// if array2 can be modified, then this is not necessary
// and you have to replace <clone> with <array2> in the block below
const clone = array2.slice(); 

const newArray = array1.map(inner => {
    return clone.splice(0, inner.length);
});

console.log(newArray);


Answer for the first version of the question

You only need .map() (twice) and a little bit of math for this.

const array1 = [
  [1, 2, 3],
  [4],
  [5],
  [6, 7]
];
const array2 = ["Banana", "Orange", "Apple", "Grape", "Pineapple", "Raspberry", "Pear"];

const newArray = array1.map(inner => {
  return inner.map(n => {
    return array2[n - 1];
  })
});

console.log(newArray);

(can be written as a one-liner but for easier readability I've used an explicit return)

about 4 years ago · Juan Pablo Isaza Relatório

0

const array1 = [["John", "Barry", "Anne"], ["Greg"], ["Tom"], ["Roy", "Rye"]];
const array2 = ["Banana", "Orange", "Apple", "Grape", "Pineapple", "Raspberry","Pear"];

let indexTracker=0;

const newArr = array1.map(nameArr => nameArr.map(_ => array2[indexTracker++]));

console.log(newArr);

about 4 years ago · Juan Pablo Isaza Relatório

0

Use Array.map() and Array.slice() to get the final result.

const array1 = [[1, 2, 3], [4], [5], [6, 7]]
const array2 = ["Banana", "Orange", "Apple", "Grape", "Pineapple", "Raspberry", "Pear"]

let index = 0;
const finalArray = array1.map((itemList) => {
  const list = array2.slice(index, index + itemList.length);
  index += itemList.length;
  return list;
});

console.log(finalArray);

about 4 years ago · Juan Pablo Isaza 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