Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to convert an array of strings to array of numbers?

I have this part of project that I need to convert a Number to an Array, then I have to add +1 to every digit
I wrote this code, still it return undefined

function Nbr1(a){
    return a.toString().split('').map(Number).forEach( (item, index) => item + 1);
}
console.log(Nbr1(12345))

and I got this result

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and when I add console.log to every item in forEach, I got this

enter image description here

>Solution :

You don’t need to use a forEach after map. map already iterates through the array.

And don’t forget to convert the array item to a number with a + before it because you generated an array of strings

function Nbr1(a) {
  return a.toString().split("").map((number) => +number + 1)
}

console.log(Nbr1(12345))

Learn more about map

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading