5

I want to create an integer or number that contains all the digits from an array of digits or string. How can I achieve that ?

for example:

digitArry = [9', '8', '7', '4', '5', '6'];

should become

integer = 987456;
3

1 Answer 1

6

You can use join and parseInt:

var digitArry = ['9', '8', '7', '4', '5', '6'];
var integer = parseInt(digitArry.join(''), 10);

console.log(integer);

EDIT: As suggested by @kay, another alternative is using + to convert string to number:

var digitArry = ['9', '8', '7', '4', '5', '6'];
var integer = +digitArry.join('');

console.log(integer);

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

8 Comments

Just nitpicking, but it's always a good idea to specify the radix in the parseInt method, even if base10 is the default.
Don't forget to pass 10 as the base
Make sure to specify the second parameter in parseInt, since some browser do not use the base 10 by default.
Never use parseInt without specifying the radix. Almost always +str is the better alternative.
@JeffNoel This has nothing to do with the browser. It's when the string starts with a 0
|

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.