将文本文件垂直转换为多维数组(不是逐行)

我在名为 的变量中获取了以下文本文件myText:


file.txt:

1,5,9

2,6,0

3,7,0

4,8,0


myText = // content of file.txt

myText我想通过对每列中的元素进行分组来获得一个如下所示的二维数组:


my2DArray = [

    [1, 2, 3, 4],

    [5, 6, 7, 8],

    [9, 0, 0, 0],

]


白板的微信
浏览 80回答 3
3回答

繁星点点滴滴

假设所有行具有相同数量的元素,您可以首先从文本构造一个二维数字数组,然后使用Array.from获取每列中的元素。let myText = `1,5,92,6,03,7,04,8,0`;const parts = myText.split('\n').map(x => x.split(',').map(Number));const res = Array.from({length: parts[0].length},    (_,i)=>Array.from({length: parts.length}, (_,j)=>parts[j][i]));console.log(JSON.stringify(res));

交互式爱情

这是一个更优化的版本(更快一点),迭代次数更少。const myText =&nbsp;`1,5,9&nbsp; &nbsp;2,6,03,7,04,8,0`;const rows = myText.split('\n');const result = [];for (let i = 0; i < rows.length; i++) {&nbsp; &nbsp; const row = rows[i].split(',');&nbsp; &nbsp; for (let j = 0; j < row.length; j++) {&nbsp; &nbsp; &nbsp; &nbsp; if (result[j] === undefined) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result[j] = [parseInt(row[j])]&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result[j].push(parseInt(row[j]))&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}console.log(result)

萧十郎

您可以使用split,map和reduce:const myText = `1,5,92,6,03,7,04,8,0`;const my2DArray = myText                   .split('\n')                   .map(row => row.split(',').map(Number)) // Reversed 2D Array                   .reduce((acc, row) => {                     if (acc.length) {                       return acc.map((r, i) => r.concat(row[i]));                     }                     return row.map(v => [v]);                   }, []); // Rotated matrix                 console.log(my2DArray);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript