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)
You could look for digits with a comma in between, replace, add brakets and parse as JSON.
var original = "547,449,737,452,767,421,669,367,478,367,440,391,403,392,385,405,375,421,336,447", array = JSON.parse('[' + original.replace(/\\d+,\\d+/g, '[$&]') + ']'); console.log(array);
This could be a nice use case for using .matchAll()
:
var original = "547,449,737,452,767,421,669,367,478,367,440,391,403,392,385,405,375,421,336,447"; var array = Array.from(original.matchAll(/(\\d+),(\\d+)/g), ([, ...m]) => m.map(Number)); console.log(array);
Using Regex and JSON.parse are costlier. Do it using array to matrix as below
const original = "547,449,737,452,767,421,669,367,478,367,440,391,403,392,385,405,375,421,336,447"; const arrayToMatrix = (array, columns) => Array(Math.ceil(array.length / columns)).fill('').reduce((acc, cur, index) => { return [...acc, [...array].splice(index * columns, columns)] }, []); const result = arrayToMatrix(original.split(','),2); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.