Luckyn
Luckyn

Reputation: 563

javascript - convert an array of strings and numbers to an array of numbers

I have an array of strings and numbers. I need to convert all items to numbers, i.e :

var a = ["42.00", 33, 12.02, "30", 10];

convert to:

[42.00, 33, 12.02, 30, 10]

Upvotes: 0

Views: 107

Answers (5)

Touffy
Touffy

Reputation: 6561

Really, what's up with writing a full paragraph of code for something this simple? This is all you need:

var a = ["42.00", 33, 12.02, "30", 10]

a.map(Number) // returns [42, 33, 12.02, 30, 10]

(note that all numbers in JavaScript are 64-bit floating-point, no point writing them explicitly as float)

Upvotes: 0

rxjmx
rxjmx

Reputation: 2181

var a = ["42.00", 33, 12.02, "30", 10];
var b = [];
a.forEach(function(num){
    b.push(parseFloat(num));
});
console.log(b);
// [42, 33, 12, 30, 10]

Or add prototype method to Array:

Array.prototype.toInt = function (a){
    var b = [];
    this.forEach(function(num){
        b.push(parseFloat(num));
    });
    return b;
}
var a = ["42.00", 33, 12.02, "30", 10];
console.log(a.toInt());

https://jsfiddle.net/0okLL93m/

I'm sure this could be written better somehow, but works pretty well.

Upvotes: 0

briosheje
briosheje

Reputation: 7446

For fallback compatibily purpose:

var a = ["42.00", 33, 12.02, "30", 10];
var out;

if (typeof(Array.prototype.map == 'function')) {
    out = a.map(function(el){ return typeof(el) !== 'number' ? parseFloat(el) : el });
}
else {
    out = [];
    for (var i = 0; i < a.length; ++i) {
        out[i] = typeof(a[i]) !== 'number' ? parseFloat(a[i]) : a[i];   
    }
}

console.log(out);

if the element is already a number it won't parse it, else it will.

if the .map function is not defined, it will procede using a regular for loop. This should be done because some browsers does not support some ECMA functions (like IE9):

enter image description here

fiddle :: http://jsfiddle.net/kndgcty8/1/

Upvotes: 1

bloodyKnuckles
bloodyKnuckles

Reputation: 12089

JavaScript Array map method:

var a = ["42.00", 33, 12.02, "30", 10]
var b = a.map(function (elem) {
    return parseInt(elem, 10)
})
console.log(b)
// [42, 33, 12, 30, 10]

JSFiddle

Upvotes: 0

Ramkumar
Ramkumar

Reputation: 191

var a = ["42.00", 33, 12.02, "30", 10];
var b=new Array();

for(i=0;i<a.length;i++)
  b[i]=parseFloat(a[i]);

alert(a);
alert(b);

Upvotes: 0

Related Questions