-1

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]
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
David Boss
  • 27
  • 5
  • 1
    Duplicate: [How to convert all elements in an array to integer in JavaScript?](https://stackoverflow.com/questions/4437916/how-to-convert-all-elements-in-an-array-to-integer-in-javascript) –  Jan 11 '22 at 18:55

2 Answers2

1

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);
Kinglish
  • 23,358
  • 3
  • 22
  • 43
0

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.

Redu
  • 25,060
  • 6
  • 56
  • 76