RulerNature RulerNature - 3 months ago 6
Javascript Question

JavaScript split() string to array of integers

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

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


If I use
split()
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]


so indicating which is string and which is number.

Answer

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]
Comments