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 ";
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 ";
You can use split() to get string array from comma separated string. If you iterate and perform mathematical operation on element of string array then that element will be treated as number by run-time cast but still you have string array. To convert comma separated string int array see the edit.
Live Demo
Output
Edit, Comma separated string to int Array In the above example the string are casted to numbers in expression but to get the int array from string array you need to convert it to number.
Solution:
You can split and convert like
Now you can use intValArray in you logic.
All of the given answers so far create a possibly unexpected result for a string like
",1,0,-1,, ,,2"
:To solve this, I've come up with the following fix:
Please note that due to
and
we cannot combine both filter steps.
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, theNumber
function orparseInt
, and add them to your array:Or, in one step, using Array
map
to convert them and applying them to one singlepush
:Edit >>
Thanks to @NickN & @connexo remarks! A filter is applicable if you by eg. want to exclude any non-numeric values: