Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Destructuring tuples in JavaScript

I’m trying to destructure a tuple:

tuple = [[1,"word",3,4,5],[1,"hello",3,4,5],[1,"word",3,4,5]]

Like so:

let destruct = [item1, item2, item3, item4, item5] = [tuple]

But everything gets assigned to item1 from the tuple. Is it possible to actually map each array from the tuple to the 5 items in the second array?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected output:

item2[0] = "word",
item2[1] = "hello

EDIT: someone answered with a tuples.map which got the desired result, but the answer has been deleted? Furthermore, is a pure destructing solution possible?

>Solution :

Use a nested map(), get the index from the first, en use that to create each ‘column’:

const [ ] = tuple[0].map((_, i) => tuple.map((_, j) => tuple[j][i]))
const tuple = [[1,"word",3,4,5],[1,"hello",3,4,5],[1,"word",3,4,5]];

const [ item1, item2, item3, item4, item5 ] = tuple[0].map((_, i) => tuple.map((_, j) => tuple[j][i]));

console.log(item2[0], item2[1]); // word hello
console.log(item4);              // [ 4, 4, 4 ]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading