简体   繁体   English

将一串逗号分隔的数字转换为二维数组

[英]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]

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.您可以使用带有%运算符的splitreduce方法来创建所需的结果。

 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.您可以查找中间有逗号的数字,替换,添加刹车并解析为 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() :这可能是使用.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.使用 Regex 和 JSON.parse 的成本更高。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM