user65165
user65165

Reputation: 972

Arrays and strings in javascripts

Array1 = ['1,2,3']

How can I retrieve the numerical values by transforming it into non-string? I've been trying parseInt, but I can only manage to get 1 as end-result.

Thanks.

Upvotes: 0

Views: 69

Answers (3)

Md Ashaduzzaman
Md Ashaduzzaman

Reputation: 4038

Generally parseInt() takes anything(most of the time string) as input and returns integer out of that input. If it doesn't get any integer then it returns NaN.

Why you are getting 1 !!!

Whenever you are using parseInt() it tries to read your input character by character. So according to your input

var Array1 = ['1,2,3'];

first it get's '1' and after that ',' (a comma, which is not a number) so it converts '1' into Integer and returns it as your result.

Solution of your problem :

var Array1 = ['1,2,3'];
//just displayed the first element of the array, use for or foreach to loop through all the elements of the array
alert(Array1[0].split(',')[0]);

Upvotes: 1

David Atchley
David Atchley

Reputation: 1204

I would re-look why you're storing a comma separated string as an array element; but, if the reasoning is valid for your particular design, the question is do you have an array with more than one comma-separated string like this?

If you can, re-work your design to actually use an array of integers, so use:

var arr = [1,2,3];

instead of ['1,2,3'].

If you are storing comma separated strings as array elements, you can get each index as an array of integers using something like the following:

var array1 = ['1,2,3', '4,5,6,7'];

function as_int_array(list, index) {
    return list[index].split(',').map(function(o) { return parseInt(o,10); });
}
console.log("2nd element: %o", as_int_array(array1, 1));
// => 2nd element: [4,5,6,7]

Hope that helps.

Upvotes: 1

elixenide
elixenide

Reputation: 44831

If you start with an array containing a string, like in your example, you need to use split().

Example:

Array1 = ['1,2,3'];
var new_array = Array1[0].split(',');  // new_array is ["1", "2", "3"]
for (var i = 0; i < new_array.length; i++) {
    new_array[i] = parseInt(new_array[i]);
}
// new_array is now [1, 2, 3]

Upvotes: 1

Related Questions