Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a one-dimensional array of integer in JavaScript that I'd like to add data from comma separated string, Is there a simple way to do this?

e.g : var strVale = "130,235,342,124 ";

share|improve this question
    
add comment

5 Answers

You can use split()

arr = strVale.split(',');
share|improve this answer
1  
w3schools is a bad resource. –  VisioN May 6 '13 at 9:56
3  
@VisioN:your link too :P –  Anoop Joshi May 6 '13 at 9:57
    
Thanks @VisioN, it is not always reliable, anyhow changed. –  Adil May 6 '13 at 9:59
    
this is wrong / just one step to the actual solution. It'll save the numbers as strings to the array, not as integers! –  Sumit Jul 22 '13 at 14:41
add comment

You can use the String split method to get the single numbers as an array of strings. Then convert them to numbers with the unary plus operator, the Number function or parseInt, and add them to your array:

var arr = [1,2,3],
    strVale = "130,235,342,124 ";
var strings = strVale.split(",");
for (var i=0; i<strVale.length; i++)
    arr.push( + strings[i] );

Or, in one step, using Array map to convert them and applying them to one single push:

arr.push.apply(arr, strVale.split(",").map(Number));
share|improve this answer
    
Brilliant use of map() –  antur123 Jun 14 '13 at 11:31
add comment

just you need to use couple of methods for this, that's it!

var strVale = "130,235,342,124";
var resultArray = strVale.split(',').map(function(strVale){return Number(strVale);});

the output will be the array of numbers.

share|improve this answer
add comment

The split() method is used to split a string into an array of substrings, and returns the new array.

Syntax:
  string.split(separator,limit)


arr =  strVale.split(',');

SEE HERE

share|improve this answer
add comment

You can split and convert like

 var strVale = "130,235,342,124 ";
 var intValArray=strVale.split(',');
 for(var i=0;i<intValArray.length;i++{
     intValArray[i]=parseInt(intValArray[i]);
}

Now you can use intValArray in you logic.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.