1

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]);
         }
}
1
  • 3
    It's incredible to see the number of fruit business trying to improve their website nowadays. Commented Jun 12, 2015 at 15:46

1 Answer 1

2

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")];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.