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.
CodePudding user response:
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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
[
[
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.
CodePudding user response:
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 );
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Using Array.prototype.reduce method,
['101','010','110'].reduce((acc,val,index)=>{
acc[index] = [...val.split("").map((item)=>parseInt(item))];
return acc;
}
,[]);