Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!