console.log(b); // prints ["1", "2", "3", "4"]
This is not correct, it actually prints [["1", "2", "3", "4"]]
(a 2d array) as you are mapping a string in an array to an array, thus, you still maintain the outer array.
Instead, you can use .flapMap()
to map the contents of the array that .split()
returns to the outer container array like so:
var a = ["1,2,3,4"];
var b = a.flatMap(val => val.split(','));
console.log(b); // prints ["1", "2", "3", "4"]
var c = b.map(x => parseInt(x));
console.log(c); // prints [1, 2, 3, 4]
Alternatively, you can also use JSON.parse()
on your string of arrays with .flatMap
to get an array of numbers like so:
var a = ["1,2,3,4"];
var b = a.flatMap(val => JSON.parse(`[${val}]`));
console.log(b); // [1, 2, 3, 4]
However, do note, .flatMap()
does currently have limited browser support, and so, instead, you may want to use .reduce()
if you have multiple elements:
var a = ["1,2,3,4"];
var b = a.reduce((acc, val) => [...acc, ...val.split(',')], []);
console.log(b); // prints [["1", "2", "3", "4"]]
var c = b.map(x => parseInt(x));
console.log(c); // prints [1, 2, 3, 4]
The advantage of using these two (three) methods is that it will work for a
values where you have multiple beginning strings such as ["1,2,3,4", "5,6,7,8"]
etc...