Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string of comma separated numbers into a 2D array

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]
like image 900
Andrew Junior Howard Avatar asked Nov 29 '25 19:11

Andrew Junior Howard


2 Answers

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);
like image 61
CertainPerformance Avatar answered Dec 01 '25 09:12

CertainPerformance


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)
like image 42
Nenad Vracar Avatar answered Dec 01 '25 08:12

Nenad Vracar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!