I have a string of numbers like so:
var original = "547,449,737,452,767,421,669,367,478,367,440,391,403,392,385,405,375,421,336,447";
And I wish to convert this string into a 2D array like so:
[[547, 449] [737, 452] [767, 421] [669, 367] [478, 367] [440, 391] [403, 392] [385, 405] [375, 421] [336, 447]]
But I'm having trouble doing it. I tried using regex:
var result = original.replace(/([-\d.]+),([-\d.]+),?/g, '[$1, $2] ').trim();
But the result was a string of the following and not an array:
[547, 449] [737, 452] [767, 421] [669, 367] [478, 367] [440, 391] [403, 392] [385, 405] [375, 421] [336, 447]
Might be easier to use a global regular expression to match two segments of digits, then split each match by comma and cast to number:
var original = "547,449,737,452,767,421,669,367,478,367,440,391,403,392,385,405,375,421,336,447";
const arr = original
.match(/\d+,\d+/g)
.map(substr => substr.split(',').map(Number));
console.log(arr);
You could use split and reduce methods with % operator to create the desired result.
var original = "547,449,737,452,767,421,669,367,478,367,440,391,403,392,385,405,375,421,336,447";
const result = original.split(',').reduce((r, e, i) => {
if (i % 2 == 0) r.push([]);
r[r.length - 1].push(e);
return r;
}, [])
console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With