0
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.

1
  • 1
    @NiettheDarkAbsol on the other hand, maybe he wants an array with one string element '1,2,3' in it :) Commented Jun 30, 2014 at 21:10

3 Answers 3

1

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]
Sign up to request clarification or add additional context in comments.

1 Comment

You should never use for (var i in new_array) to iterate an array. That iterates properties of the object, not only elements of the array which is sometimes the same thing, but not always. Use for (var i = 0; i < new_array.length; i++) instead.
1

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.

Comments

1

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

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.