-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]
1

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Wow that's neat! I like it
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.

1 Comment

Or use a RegExp in split()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.