1

I'm wondering how to convert an array of strings

lines = ['101','010','110'];

to an array of arrays like this:

x = [
[1,0,1],
[0,1,0],
[1,1,0]'
]

I already tried

x = (lines.forEach(e => (e.split(''))))

and realized String.split doesnt mutate the current string. So my next step was to create a new array with these values.

x = new Array(lines.forEach(e => (e.split(''))))

My thoughts behind this line: The code should take an element (e) of the lines array and apply the split funtion to it. (which is does when i console.log() it.) BUT it doesnt apply it to the new array.

Maybe the problem is, that it doesn't loop through x but maybe i overlook another fact.

Dr0nhp
  • 13
  • 3

3 Answers3

4

You can use .map(Number) on the split() result to convert them to a Number as expected

const lines = ['101','010','110'];
const res = lines.map(l => l.split('').map(Number));

console.log(res);
[
  [
    1,
    0,
    1
  ],
  [
    0,
    1,
    0
  ],
  [
    1,
    1,
    0
  ]
]

Regarding your forEach solution, since forEach does not return anything, x stays undefined

You could define an empty array, and push your split() into that empty array, but using map() is a more readable/clean solution.

For more information about map() vs forEach(), please take a look at this stackoverflow answer.

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    @OP - For what it's worth, in *general*, using a function as a `map` callback that isn't designed for it is chancy, but it's fine in the case of the `Number` function (it wouldn't be for `parseInt`, though, as an example). For more number conversion options (since `Number` will give you `0` for `""`), see [my answer here](https://stackoverflow.com/questions/28994839/why-does-string-to-number-comparison-work-in-javascript/28994875#28994875). – T.J. Crowder Dec 03 '21 at 11:54
  • 3
    Would be good to explain why `forEach` didn't work. – T.J. Crowder Dec 03 '21 at 11:55
  • 1
    Thank you for this futher explanation! – Dr0nhp Dec 03 '21 at 12:01
0

As per @OstoneO's answer, Array#map() is the most appropriate method to use, hence it would be my first choice.

Array#forEach()'s return value is undefined because it's not designed to return a value; it is a loop and should be used as such:

const lines = ['101','010','110'];

const x = [];
lines.forEach( line => x.push( line.split('').map(n => +n) ) );

console.log( x );
PeterKA
  • 24,158
  • 5
  • 26
  • 48
-1

Using Array.prototype.reduce method,

 ['101','010','110'].reduce((acc,val,index)=>{
    acc[index] = [...val.split("").map((item)=>parseInt(item))];
    return acc;

}
,[]);
Pranay Binju
  • 591
  • 1
  • 6
  • 14