RFFD
RFFD

Reputation: 5

Underscore _.each iterate on array

I have this variable and using underscore I'm trying to map the result into a new array. I'm trying to iterate on the first value of newarr. Right now im doing it manually, I've tried different ways but I'm not getting it right. I want to be able to iterate over the first value of newarr and get [0] for that.

var stripped = _.map( newarr[0][0].split(","), function(s){ return parseFloat(s);});
var stripped2 = _.map( newarr[1][0].split(","), function(s){ return parseFloat(s);});
var stripped3 = _.map( newarr[2][0].split(","), function(s){ return parseFloat(s);});

Upvotes: 0

Views: 162

Answers (2)

Jordan Running
Jordan Running

Reputation: 106027

Is this what you want?

var newarr = [ ["40.735641, -73.990568"],
               ["40.736484, -73.989951"],
               ["40.736484, -73.989951"] ];

var floatArr = _.map(newarr, function (coordsArr) { 
  var coords = coordsArr[0].split(',');
  return [ parseFloat( coords[0] ), parseFloat( coords[1] ) ];
})

console.log(floatArr);
// => [ [ 40.735641, -73.990568],
//      [ 40.736484, -73.989951],
//      [ 40.736484, -73.989951] ]

Note that you could use _.map on the return line, but since there's always going to be two elements that's a lot of unnecessary complexity.

Upvotes: 0

Esaevian
Esaevian

Reputation: 1727

Is there a reason you can't just do a loop on newarr?

var strippedarr = [];

for (int i = 0; i < newarr.length; i++) { strippedarr[i] = _.map(newarr[i][0].split(","), function(s){ return parseFloat(s); }); }

Upvotes: 2

Related Questions