2

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?

royhowie
  • 11,075
  • 14
  • 50
  • 67
petehallw
  • 1,014
  • 6
  • 21
  • 49
  • You want to [flatten](http://stackoverflow.com/q/10865025/218196) the array and [convert each element to a number](http://stackoverflow.com/q/23457895/218196). – Felix Kling Nov 17 '14 at 17:34

2 Answers2

8

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);
dfsq
  • 191,768
  • 25
  • 236
  • 258
5

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]));
  }
}
Shriike
  • 1,351
  • 9
  • 20
  • Thank you for your answer. The other answer came just before you but this was also helpful! +1 – petehallw Nov 17 '14 at 17:44
  • In fact this answer is more generic so it should be accepted. – petehallw Nov 17 '14 at 17:49
  • @petehallw how is this answer more generic…? – royhowie Nov 17 '14 at 18:23
  • @royhowie kind of has a point. dfsq's solution when he started wasn't quite as good as mine, he didn't map the results to numbers. But after his edit it's just as generic of a solution, just seems more compact. – Shriike Nov 17 '14 at 18:28
  • @Shriike You should probably add `var` keywords to `y` and `i` definitions. – dfsq Nov 17 '14 at 18:32
  • @Shriike I didn't mean that your answer shouldn't've been accepted. I was just wondering why the OP thought your answer was more generic. – royhowie Nov 18 '14 at 06:41
  • @royhowie that's fine, but I do think the other answer should have been accepted over mine :) I was just agreeing with you that the other answer is just as generic but more compact. – Shriike Nov 18 '14 at 13:18