Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split() a string to an array of integers

I have a string that should be executed as an array:

var q = "The, 1, 2, Fox, Jumped, 3, Over, 4";
var z = q.split(',');

If I use split(), it will create an array of strings:

[‘The’, '1', '2', ‘Fox’, ‘Jumped’, '3', ‘Over’, '4'] 

and I don’t need that. I need an array like:

[‘The’, 1, 2, ‘Fox’, ‘Jumped’, 3, ‘Over’, 4]

indicating which is a string and which is a number.

like image 279
RulerNature Avatar asked Aug 12 '16 06:08

RulerNature


4 Answers

One option is using the Number constructor which returns a number or NaN:

var res = q.split(',').map(el => {
  let n = Number(el);
  return n === 0 ? n : n || el;
});

// > "The, 1, 2, Fox, Jumped, 3.33, Over, -0"
// < ["The", 1, 2, " Fox", " Jumped", 3.33, " Over", -0]

edit: If the above condition is confusing you can replace it with the following condition which was suggested by Bergi:

return isNaN(n) ? el : n;

In case that you want to trim the string elements you can also use the String.prototype.trim method:

return isNaN(n) ? el.trim() : n;
like image 111
undefined Avatar answered Oct 15 '22 13:10

undefined


  1. You can use Number function to convert a Stringified number to an actual number.
  2. The Number function would return NaN, if it is not able to convert a string to a Number.

You can use these two facts to our advantage and write something like this

"The, 1, 2, Fox, Jumped, 3, Over, 4".split(/\s*,\s*/g).map(d => Number(d) || d);
// [ 'The', 1, 2, 'Fox', 'Jumped', 3, 'Over', 4 ]

Since, NaN is Falsy (Boolean(NaN) is false), if the Number is not able to convert a string to a number, the actual value will be returned as it is.

like image 37
thefourtheye Avatar answered Oct 15 '22 15:10

thefourtheye


var q = "The, 1, 2, Fox, Jumped, 3, Over, 4";
var z = q.split(',');

You could use Array.map, which returns a new array

var newAr = z.map(item => parseInt(item) ? parseInt(item) : item); 

Will output

["The", 1, 2, " Fox", " Jumped", 3, " Over", 4]

like image 20
kris Avatar answered Oct 15 '22 15:10

kris


//from the linked SO answer
function isNumeric(n) { 
  return !isNaN(parseFloat(n)) && isFinite(n);
}

var q = "The, 1, 2, Fox, Jumped, 3, Over, 4";
var z = q.trim().split(/\s*,\s*/).map(function(word) {
  return isNumeric(word) ? Number(word) : word;
});

console.log(z);

How does this work?

isNumeric

It's important to note that you need a way of detecting what is and isn't a number. I suggest using the implementation shown here (the same one as my example) as it's robust and would not throw false positives or false negatives. A lot of the answers here will ignore some valid numbers (e.g., +3 or -3) or parse something invalid as a number (e.g., "").

Let's assume you have a function called isNumeric() that returns a boolean for whether an input is numeric or not. If need be, you might need to alter the implementation to suit your needs, e.g., if you only want to use whole number or only positive numbers.

Splitting into separate words

The string you have would need to be separated into separate chunks of words. This is done in the following fashion

var input = " The, 1, 2 , Fox  , Jumped  , 3, Over, 4     ";
input.trim() //make sure there are no beginning and ending spaces
    .split(/\s*,\s*/); //split on a comma surrounded by any amount of spaces. That removes spaces from start/end of each of the words
//["The", "1", "2", "Fox", "Jumped", "3", "Over", "4"]

Using .map

The map() method can be ran on an array to transform it into a new array. This us done by transforming each element using a callback function. The callback given simply checks if a word is actually a number - if so, it parses it as a number using Number for explicit type conversion. Note that you should NOT have new Number(word) as that creates a Number object, not the numeric primitive type.

It might be useful to note that implicit conversion could be done using the + operator. For example:

+"500" //500
+"hello" //NaN

To the in the beginning of my answer could use +word instead of Number(word) but just I find explicit conversion to be easier to understand.

like image 21
VLAZ Avatar answered Oct 15 '22 15:10

VLAZ