Javascript: How to force .split() to create numArray? [duplicate]

  • A+
Category:Languages

This question already has an answer here:

This is just an example, I have much more amount of data:

var str = "3.0;4.5;5.2;6.6"; var res = str.split(";"); console.log(res); 

The output will be an array of strings. How can I have array of numbers without going through the existing array again?

 


...without going through the existing array again?

That's tricky. You can't with split, because split produces an array of strings. You could do it in a single pass with a regular expression, building the array yourself:

var rex = /[^;]+/g; var str = "3.0;4.5;5.2;6.6"; var match; var res = []; while ((match = rex.exec(str)) != null) {   res.push(+match[0]); } console.log(res);

Or actually, that's more overhead than necessary, just indexOf and substring will do:

var str = "3.0;4.5;5.2;6.6"; var start = 0, end; var res = []; while ((end = str.indexOf(";", start)) !== -1) {   res.push(+str.substring(start, end));   start = end + 1; } if (start < str.length) {   res.push(+str.substring(start)); } console.log(res);

KooiInc's answer uses replace to do the loop for us, which is clever.


That said, unless you have a truly massive array, going through the array again is simpler:

var res = str.split(";").map(entry => +entry); 

In the above, I convert from string to number using a unary +. That's only one of many ways, and they have pros and cons. I do a rundown of the options in this answer.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: