0

I have a list of tuple in string format.

let tuple_list= '[("AB", "CD"), ("EF", "GH"), ("IJ", "KL")]'

I want it to convert in an array.

("AB", "CD" , "EF", "GH", "IJ", "KL")

Please let me know how can I do that.

  • Theres no such thing as tuples in Javascript (https://stackoverflow.com/questions/60109623/does-javascript-have-tuples) - the same functionality is achieved with a fixed length array. But the bracket notation like you have just doesnt exist. So you're stuck with parsing this string yourself. – Jamiec May 24 '22 at 10:26
  • Hello @Jamiec, it's not about the brackets. The 1st example is the one I have. And the second example is how I want as an array. I might have used the wrong brackets to denote an array in javascript, but I meant it to get converted in an array like that. – Argha Kamal Chakraborty May 24 '22 at 10:32
  • Hello @ArghaKamalChakraborty check I've edited my answer – Ankit Tiwari May 24 '22 at 12:04

3 Answers3

1
let parsed = '[("AB", "CD"), ("EF", "GH"), ("IJ", "KL")]';

function parseTuple(t) {
    return JSON.parse(t.replace(/\(/g, "").replace(/\)/g, ""));
}

var result = parseTuple(parsed);
console.log(result);
Solomon
  • 159
  • 1
  • 13
0

JavaScript does not support tuples so you've to convert it into array so you can do like this

let tuple_list = '[("AB", "CD"), ("EF", "GH"), ("IJ", "KL")]'
tuple_list = tuple_list.replaceAll("(","").replaceAll(")","")
let result = JSON.parse(tuple_list)
console.log(result)

Andif you want nested array do like this

let tuple_list = JSON.parse('[("AB", "CD"), ("EF", "GH"), ("IJ", "KL")]'.replaceAll("(", "[").replaceAll(")", "]"))

console.log(tuple_list)
Ankit Tiwari
  • 4,438
  • 4
  • 14
  • 41
0

Try this:

JSON.parse('[("AB", "CD"), ("EF", "GH"), ("IJ", "KL")]'.replaceAll("(", "[").replaceAll(")", "]")).flat()
max li
  • 2,417
  • 4
  • 30
  • 44