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

170
Visualizações
JS Javascript - How to put array values in another array by indexes?

I have this array/object:

const template = {0: [0, 1, 2, 3, 4, 5], 1: [0, 1, 2, 3, 4, 6]}
// I have the above but happy to convert the below if it helps:
//const templateArr = [[0, 1, 2, 3, 4, 5],[0, 1, 2, 3, 4, 6]]

Then I have an array that I want to map into that sequence:

const myArray = ["Q","W","A","S","Z","X,"E","R","D"] // for example

My intention it to have following result:

let myResult = [["Q", "W", "A", "S", "Z", "X"],["Q", "W", "A", "S", "Z", "E"]]

So all the values of myArray are in the positions set by template.

I'm not sure if I should use .map() or something else... Can someone point me in the right direction??

Thank you so much!

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

0

Yes, .map() is the right tool here. You can use two, one outer one to map over your inner arrays from templateArr, and then an inner map to map over the numbers (indexes) in your inner arrays, which will transform (ie: map) each number to the corresponding value at the index from myArray:

const templateArr = [[0, 1, 2, 3, 4, 5],[0, 1, 2, 3, 4, 6]];
const myArray = ["Q","W","A","S","Z","X","E","R","D"];

const res = templateArr.map(inner => inner.map(idx => myArray[idx]));
console.log(JSON.stringify(res)); // JSON.stringify to pretty-print

about 4 years ago · Juan Pablo Isaza Relatório

0

Object.values will convert your template into array of arrays, then simply do map over it and another inner map over indicies and replace them with particular letter from myArray.

Code:

const template = {0: [0, 1, 2, 3, 4, 5], 1: [0, 1, 2, 3, 4, 6]}

const myArray = ["Q","W","A","S","Z","X","E","R","D"]

const res = Object.values(template)
                  .map(a => a.map(idx => myArray[idx] ?? null))

console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore this */

about 4 years ago · Juan Pablo Isaza Relatório

0

I think this should work:

const res = templateArr.map( (arr) => {
    
    return arr.map( (index) => {
        return myArray[index]
    })
})
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