Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

how to convert items into integer in array with different values

Is it possible to convert items that are numbers into integer but leave those that are not as a string?

For example

From this:

var a = ["1", "2","b","k","blue","100"]

To this:

var a = [1, 2,"b","k","blue",100]

Thanks

3 Answers

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Hi Natalie Man

Sure. Here's one simple way:

for (var i = 0; i < a.length; i++ ) {
 if ( ! isNaN(a[i]) ) {
     a[i] = +a[i];
 }   
}

If your array has Boolean values -- true or false -- you'll need to test for those as well, since JavaScript converts those to numbers:

for (var i = 0; i < a.length; i++ ) {
 if ( ! isNaN(a[i]) && typeof a[i] !== 'boolean') {
     a[i] = +a[i];
 }   
}

The + operator is a quick way to convert a string with a number to a number. It works with both integers and floating point values. For example, +'1.4' will become 1.4.

Hi Natalie. there should be better solution, but I would use if like this:

isNaN(parseInt(string)) ? string : parseInt(string);

And because this is an array, this could be done:

var array = [1, 2,"b","k","blue",100];
for(i=0; i<array.length; i++) {
  array[i] = isNaN(parseInt(array[i])) ? array[i] : parseInt(array[i]);
}

Dave's answer came while I was typing, and I didn't consider float number! His should be a better answer definitely :)

Thanks the reply I'll give them a try and see how it goes :)