Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
You want to flatten the array and convert each element to a number. –  Felix Kling 1 hour ago

2 Answers 2

up vote 3 down vote accepted

You could do something like this.

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

share|improve this answer
    
Thank you for your answer. The other answer came just before you but this was also helpful! +1 –  petehallw 1 hour ago
    
In fact this answer is more generic so it should be accepted. –  petehallw 1 hour ago
    
@petehallw how is this answer more generic…? –  royhowie 32 mins ago
    
@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 27 mins ago
    
@Shriike You should probably add var keywords to y and i definitions. –  dfsq 23 mins ago

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);
share|improve this answer
    
This worked for me, thank you! –  petehallw 1 hour ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.