Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert comma separated string into numeric array in javascript

Tags:

javascript

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 ";

like image 830
user2256371 Avatar asked May 06 '13 09:05

user2256371


People also ask

How can I convert a comma separated string to an array JavaScript?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.

How can you convert information consisting of comma separated values into an array?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.

How do I convert a string to an array in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


1 Answers

? "123,87,65".split(",").map(Number) > [123, 87, 65] 

Edit >>

Thanks to @NickN & @connexo remarks! A filter is applicable if you by eg. want to exclude any non-numeric values:

?", ,0,,6, 45,x78,94c".split(",").filter(x => x.trim().length && !isNaN(x)).map(Number) > [0, 6, 45] 
like image 118
serge Avatar answered Sep 20 '22 18:09

serge