Home > Software design >  Destructuring tuples in JavaScript
Destructuring tuples in JavaScript

Time:03-30

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?

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?

CodePudding user response:

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 ]

CodePudding user response:

You have extra brackets around tuple, try this

const tuple = [[1,"word",3,4,5],[2,"word",3,4,5],[3,"word",3,4,5]]
const [item1, item2, item3, item4, item5] = tuple

console.log(item3)

CodePudding user response:

you can destructure any array or object in javascript

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

let [item1, item2, item3] = tuple

you can even get the nested value as follows

let [item1, [one, word, three], item3] = tuple;
console.log(one)  // 1
console.log(word)  // 'word'
console.log(three)  // 3
  • Related