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

177
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 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