Home > OS >  how to convert an array of strings to array of numbers?
how to convert an array of strings to array of numbers?

Time:12-24

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

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

enter image description here

CodePudding user response:

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

CodePudding user response:

See short example below with usage of parseInt(). No extra forEach required.

function Nbr1(a){
    return a.toString().split('').map((number)=>{
        return parseInt(number)   1
    })    
}
console.log(Nbr1(12345))

  • Related