I'm trying to convert a string of numbers into an array of elements with each number. I thought parseInt would convert the string to numbers but I'm a bit lost now.
const str = '1 2 3 4';
let words = parseInt(str);
words = str.split(' ');
which results in
Array ["1", "2", "3", "4"]
However, I would like the result to be
[1, 2, 3, 4]
You can apply a little map function to do that. When you're doing a simple conversion like this, you can use a single method in the map argument as a shortcut
str.split(' ').map(Number)
is the same as
str.split(' ').map(n => Number(n))
which is the same as
str.split(' ').map(n => {
return Number(n);
})
const str = '1 2 3 4';
let words = str.split(' ').map(Number)
console.log(words);
str.split(' ').map(Number) is not a wrong answer for the given data but what if you are given a string like '1 2 3 4'? The result would be [1, 0, 0, 0, 2, 3, 0, 0, 0, 4].
So perhaps
[...str].reduce((r,c) => c === " " ? r : (r.push(+c),r),[]);
or
[...str].reduce((r,c) => c === " " ? r : r.concat(+c),[]);
might just do better.