简体   繁体   中英

How to convert comma separated string into numeric array in 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?

eg: var strVale = "130,235,342,124 ";

? "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]

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 .

arr = strVale.split(',');

Live Demo

var strVale = "130,235,342,124";
arr = strVale.split(',');
for(i=0; i < arr.length; i++)
    console.log(arr[i] + " * 2 = " + (arr[i])*2);

Output

130 * 2 = 260
235 * 2 = 470
342 * 2 = 684
124 * 2 = 248

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.

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

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

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.

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

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.

Solution:

var answerInt = [];
var answerString = "1,2,3,4";
answerString.split(',').forEach(function (item) {
   answerInt.push(parseInt(item))
});

All of the given answers so far create a possibly unexpected result for a string like ",1,0,-1,, ,,2" :

",1,0,-1,,  ,,2".split(",").map(Number).filter(x => !isNaN(x))
// [0, 1, 0, -1, 0, 0, 0, 2]

To solve this, I've come up with the following fix:

",1,0,-1,,  ,,2".split(',').filter(x => x.trim() !== "").map(Number).filter(x => !isNaN(x))
// [1, 0, -1, 2]

Please note that due to

isNaN("") // false!

and

isNaN(" ") // false

we cannot combine both filter steps.

This is an easy and quick solution when the string value is proper with the comma(,).

But if the string is with the last character with the comma, Which makes a blank array element, and this is also removed extra spaces around it.

"123,234,345,"

So I suggest using push()

var arr = [], str="123,234,345,"
str.split(",").map(function(item){
    if(item.trim()!=''){arr.push(item.trim())}
})

There are good solutions in this post but I would like to add one more. Instead of using filter and map I would suggest to use reduce to iterate through all the items just once.

Also I will compare it with the use of a regex looking for digits. Please evaluate which method fits your needs. Here are the examples:

 const strA = ',1,0,-2,a3 , 4b,a5b ,21, 6 7,, 8.1' const arrayOfNumbersA = strA.split(',').reduce((acc, val) => val && !Number.isNaN(+val) ? acc.push(+val) && acc : acc, []) console.log(arrayOfNumbersA) // => [1, 0, -2, 21, 8.1] - As you can see in the output the negative numbers // do work and if the number have characters before or after // the numbers are removed from since they are treated like NaN. // Note: in this case the comma is the delimiting each number that will be evaluated in the reduce const arrayOfNumbersB = strA.match(/[\\d.]+/g).map(Number) console.log(arrayOfNumbersB) // => [1, 0, 2, 3, 4, 5, 21, 6, 7, 8.1] - As you can see in the output the negative numbers // are transformed to positives and if the number have characters before or after // the numbers placed any way. //Note: that in this case the regex is looking for digits no matter how they are separated. // FYI: seeing all the steps using the reduce method const arrayOfNumbersC = strA.split(',').reduce((acc, val) => { if(val && !Number.isNaN(+val)) { acc.push(+val) } return acc }, []) console.log(arrayOfNumbersC) // => [1, 0, -2, 21, 8.1]

In order to also take string value and avoid crushing we can solve it this way

 let strVale = "130,235,342,124 ";
 let unformattedArray =strVale.split(',');

 const formatArray = (unformattedArray) => {
    if (unformattedArray.map(Number).includes(NaN)) {
    return unformattedArray;
}
else {
  return unformattedArray.map(Number);
}
}
    
  //then every time we want to format we call our function to format for us
 console.log(formatArray(unformattedArray));
 // or asign a value

  let foramttedArray =  formatArray(unformattedArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM