How can I turn a string of numbers into a Matrix?

Asked

Viewed 43 times

0

I’m doing an exercise where I should extract rows and columns from a string, creating an array.

Input let str = '1 2 3\n4 5 6\n7 8 9', I wrote a code that returns: [ '4 5 6' ], but I’d like him to return something like: [4, 5, 6] (not between quotes). How can I do this?

let str = '1 2 3\n4 5 6\n7 8 9'
let arr = str.split('\n');
    let rowResult = [];
    let rowFinalResult = [];

    for(let i = 0; i < arr.length; i++){
        rowResult = arr[i];
        rowFinalResult.push([rowResult]);
    }
    console.log(rowFinalResult[1]);

2 answers

2


With the str.split('\n'), you are splitting the original string a array with three other strings, separated by '\n'.

However, for each of these three new strings, you must separate them again so as to "individualize" each numeric string (by separating by space ' '). Behold:

let str = '1 2 3\n4 5 6\n7 8 9';

let arr = str.split('\n');
for (let i = 0; i < arr.length; i++) {
  arr[i] = arr[i].split(' ');
}

console.log(arr);

To turn each string into a number, we can use the map. Note in the above code that the expression arr[i].split(' ') returns a array. Thus, using the Array.prototype.map, we can map each element to a number (by converting them using the parseInt).

let str = '1 2 3\n4 5 6\n7 8 9';

let arr = str.split('\n');
for (let i = 0; i < arr.length; i++) {
  arr[i] = arr[i]
    .split(' ')
    .map((str) => parseInt(str, 10));
}

console.log(arr);

  • 1

    I found your answer very good, simple, practical and well explained. Thank you! Solved my problem

-1

In this case, what you would need to do is the following, when you get the "rowResult", you get a string where the numbers are separated by spaces. If you replace the space by comma, you will arrive at the desired result, this can be done using the "replaceAll" method. Your code would look like this:

let str = '1 2 3\n4 5 6\n7 8 9'
let arr = str.split('\n');
let rowResult = [];
let rowFinalResult = [];

for(let i = 0; i < arr.length; i++){
    rowResult = arr[i];
    rowFinalResult.push(rowResult.replaceAll(' ',','));
}
console.log(rowFinalResult[1]);
  • I had thought of something of the kind too, but without using replaceAll. When I tested the code, the error that rowResult.replaceAll is not a function was returned, what could have happened? Thanks for the reply!

  • 2

    @ju4ncrls, the replaceAll probably didn’t work because your running environment still doesn’t support it. As you can check here, the support is not yet the best because this edition of Ecmascript has not even been released (Ecmascript 2021). To test if your environment supports it, simply use the expression: typeof String.prototype.replaceAll. Return undefined, you will not be able to use it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.