user4561667
user4561667

Reputation: 23

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!

Upvotes: 1

Views: 370

Answers (3)

ulou
ulou

Reputation: 5863

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

Upvotes: 1

Joel Imbergamo
Joel Imbergamo

Reputation: 369

I think this should work:

const res = templateArr.map( (arr) => {
    
    return arr.map( (index) => {
        return myArray[index]
    })
})

Upvotes: 0

Nick Parsons
Nick Parsons

Reputation: 50844

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

Upvotes: 3

Related Questions