1

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

3
  • 1
    Use map instead of forEach Commented Dec 23, 2021 at 11:29
  • 1
    The documentation of .forEach() tells you that .forEach() does not return anything: "Return value: undefined." Commented Dec 23, 2021 at 11:30
  • 1
    What about 9? should it be replaced with 10 or 0? Commented Dec 23, 2021 at 11:41

2 Answers 2

1

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

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

6 Comments

"...because you generated an array of strings" - No, OP did not. The conversion is done by .map(Number) (the capital N makes the difference ;))
.split returns an array of strings. String.prototype.split()
The script is a.toString().split('').map(Number) and .map(Number) does the conversion
That doesn't make the statement "because you generated an array of strings" wrong
"And don't forget to convert the array item to a number with a + before it because you generated an array of strings" - Is wrong because OP converted them into numbers before the +1. You removed the conversion and added it again with the unary +.
|
0

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

Comments

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.