Splitting an array of strings to an array of floats in JavaScript

5.2k views Asked by At

I am trying to split an array of strings, called 'vertices' and store it as an array of floats.

Currently the array of strings contains three elemets: ["0 1 0", "1 -1 0", '-1 -1 0"]

What I need is an array of floats containing all these digits as individual elements: [0, 1, 0, 1, -1, 0, -1, -1, 0]

I used the split() function as follows:

for(y = 0; y < vertices.length; y++)
{
    vertices[y] = vertices[y].split(" "); 
}

...which gives me what looks to be what I am after except it is still made up of three arrays of strings.

How might I use parseFloat() with split() to ensure all elements are separate and of type float?

2

There are 2 answers

0
dfsq On BEST ANSWER

You can use Array.prototype.reduce method for this:

var result = ["0 1 0", "1 -1 0", "-1 -1 0"].reduce(function(prev, curr) {
    return prev.concat(curr.split(' ').map(Number));
}, []);

alert(result); // [0, 1, 0, 1, -1, 0, -1, -1, 0]

Instead of .map(Number) you can use .map(parseFloat) of course if you need.

Or even shorter:

var result = ["0 1 0", "1 -1 0", "-1 -1 0"].join(' ').split(' ').map(Number);
7
Shriike On

You could do something like this.

var res = []
for (var y = 0; y < vertices.length; y++) {
  var temp = vertices[y].split(" ");
  for (var i = 0; i < temp.length; i++) {
    res.push(parseFloat(temp[i]));
  }
}