0

I've got data of this sort:

data = 
"1 2 3;
2 3 4;
5 6 7;
8 9 10;"

I'd like the data to look like this:

[
  [1,2,3],
  [2,3,4],
  [5,6,7],
  [8,9,10]
]

I've tried this approach, but to no avail:

var data = fs.readFileSync('data.txt', 'utf8')
var two_dim_array = [];
var current_row_as_array = [];
for(var i=0;i<4;i++){
    data = data.split(";\n");
    data[i] = [];
    for(var j=0;j<data[i].length;j++){
        current_row_as_array = data[i].split(" ")
    }
    two_dim_array.push(current_row_as_array);
}
console.log(two_dim_array);

Thanks, Nakul

Nakul Tiruviluamala
  • 523
  • 1
  • 3
  • 15
  • 2
    What is the purpose of your outer loop? Where does the `2` come from? What is the purpose of setting `data[i] = [];`? `data[i].length` will always be `0` after that, so the inner loop never executes. Even if it would, `current_row_as_array` gets overwritten with each iteration of the inner loop. You’ll need to rethink your logic. Familiarize yourself with [how to access and process nested objects, arrays or JSON](https://stackoverflow.com/q/11922383/4642212) and use the available [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Methods) methods. – Sebastian Simon Nov 13 '20 at 06:18

1 Answers1

1

You can use String.split to split your original data on the ; (followed by optional whitespace e.g. newline - this is most easily done with a regex); Array.filter to remove the blank entry from that array (caused by the trailing ; in the string); then use Array.map to apply String.split to split those strings by space; then finally use Array.map to convert those values to integers using parseInt:

const data = "1 2 3;\
2 3 4;\
5 6 7;\
8 9 10;"

const result = data
  .split(/;\s*/)
  .filter(Boolean)
  .map(s => s.split(' ').map(v => parseInt(v))); console.log(result);
Nick
  • 138,499
  • 22
  • 57
  • 95