Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
ParseInt a string to numbers in an array

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]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!