Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 845
user3719454 Avatar asked Apr 15 '26 10:04

user3719454


2 Answers

...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.

like image 111
T.J. Crowder Avatar answered Apr 17 '26 00:04

T.J. Crowder


You can use map():

var str = "3.0;4.5;5.2;6.6";
var res = str.split(";").map(Number);
console.log(res);
like image 24
Mamun Avatar answered Apr 17 '26 00:04

Mamun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!