loli
loli

Reputation: 1068

Efficient way to turn a string to a 2d array in Javascript

I need to check from a string, if a given fruit has the correct amount at a given date. I am turning the string into a 2d array and iterating over the columns.This code works, but I want to know : is there a better way to do it? I feel like this could be done avoiding 4 for loops.

function verifyFruit(name, date, currentValue) {...}
var data = "Date,Apple,Pear\n2015/04/05,2,3\n2015/04/06,8,6"
var rows = data.split('\n');
var colCount = rows[0].split(',').length;
var arr = [];
for (var i = 0; i < rows.length; i++) {
    for (var j = 0; j < colCount; j++) {
         var temp = rows[i].split(',');
         if (!arr[i]) arr[i] = []
             arr[i][j] = temp[j];
         }
}
for (var i = 1; i < colCount; i++) {
    for (var j = 1; j < rows.length; j++) {
         verifyFruit(arr[0][i], arr[j][0], arr[j][i]);
         }
}

Upvotes: 1

Views: 48

Answers (1)

user2033671
user2033671

Reputation:

This would be a good candidate for Array.prototype.map

var data = "Date,Apple,Pear\n2015/04/05,2,3\n2015/04/06,8,6"
var parsedData = data.split("\n").map(function(row){return row.split(",");})

What map does is iterate over an array and applies a projection function on each element returning a new array as the result.

You can visualize what is happening like this:

function projection(csv){ return csv.split(",");}
var mappedArray = [projection("Date,Apple,Pear"),projection("2015/04/05,2,3"),projection("2015/04/06,8,6")];

Upvotes: 2

Related Questions