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.
3 Answers 3
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.
3 Comments
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.forEach didn't work.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 );
Comments
Using Array.prototype.reduce method,
['101','010','110'].reduce((acc,val,index)=>{
acc[index] = [...val.split("").map((item)=>parseInt(item))];
return acc;
}
,[]);