5

I am trying to convert an array of strings into an array of integers in jquery.

Here is my attempt:

var cdata = data.values.split(",");
$.each( cdata, function(i, l){
   l = parseInt(l);
});
4
  • 2
    I'm sure that with a tiny bit of thought you can do it yourself. Think about it. Think about it really hard. Commented Aug 22, 2011 at 0:31
  • why use jquery in this case when a simple javascript loop would be sufficient? What is the goal in using jQuery? Commented Aug 22, 2011 at 0:34
  • 4
    You really should avoid calling parseInt() without specifying a radix. Commented Aug 22, 2011 at 0:37
  • I agree about always specifying a parseInt() radix, but I'd also suggest that parseInt() is the wrong choice except where you specifically want to deal with non-base-10 numbers or where you want to ignore non-digit characters at the end of the source string. Pablo's answer incorporates just one of the better options. Commented Aug 22, 2011 at 0:47

3 Answers 3

20

I think that you not need use Jquery for this case. In javascript pure:

var str = "1,2,3";
var ArrayOfInts = str.split(',').map(Number); //Output: [1,2,3]

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

Comments

8
// Use jQuery
$('.usesJQuery');

// Do what you want to acomplish with a plain old Javascript loop
var cdata = data.values.split(",");
for(var i = 0; i < cdata.length; i++)
    cdata[i] = parseInt(cdata[i], 10);

12 Comments

Or just: cdata[i] = +cdata[i];. But the excercise seems rathter pointless since strings can be converted to numbers in the expression that needs them as numbers.
+foo is a shorthand for parseInt(foo, 10)
Not really, if foo = '10 dollars'; then parseInt() works but + doesn't.
Also parseInt() is a bit more clear/readable than a unary +, in my opinion. Conciseness isn't everything.
+foo is a shorthand for new Number
|
6
var cdata = data.values.split(",");
$.map( cdata, function(i, l){
   return +l;
});

Without jQuery (using the browsers native map method):

"1,2,3,4,5,6".split(',').map(function(e) {return +e});

2 Comments

Array.prototype.map is not widely supported, it should be feature tested first and an alternative provided if not available.
There's no point in adding the for solution, @PaulPRO covered it really good. I'm leaving this for the sake of completion only (since it's not mentioned elsewhere)

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.