Search code examples
javascriptparseint

Convert CSV string to an array without .split()


I am trying to come up with a function that will take any string and output an array of numbers and strings without using .split(). Below are the tests it needs to pass and a function that passes the tests currently. I am curious about how other people would solve this.

function csvParse(inputString) {
   var outputArray = [];
   var inputArray = inputString.split(',');
   for (var i =0; i < inputArray.length; i++) {
     if (!Number.isNaN(+inputArray[i])) {
       outputArray.push(+inputArray[i]);
   } else {
     outputArray.push(inputArray[i].replace(/['"]+/g,'').trim());
   }
   }
   return outputArray;
};

describe('CSV Parse', function() {
  it('should parse a string of integers correctly', function() {
    var input = '3,7,9,1,25';
    var output = [ 3, 7, 9, 1, 25 ];
    expect(csvParse(input)).to.deep.equal(output);
  });
  it('should parse a string of strings correctly', function() {
    var input = '"3","7","9","1","25"';
    var output = ["3", "7", "9", "1", "25"];
    expect(csvParse(input)).to.deep.equal(output);
  });
  it('should parse a string of integers and strings correctly', function() {
    var input = '1, "one", 2, "two", 3, "three"';
    var output = [1, "one", 2, "two", 3, "three"];
    expect(csvParse(input)).to.deep.equal(output);
  });
});

Solution

  • Basic JS solution just replacing the split method as you asked (fiddle here)

    function dumbComaSplit(inputString) {
       var strArray = [];
       var tmpStr = "";
       for (var i = 0; i < inputString.length; i++) {
            if (inputString.charAt(i) == ',') {
                strArray.push(tmpStr);
                tmpStr = "";
                continue;
            }
            tmpStr += inputString.charAt(i);
        }
        strArray.push(tmpStr);
        return strArray;
    };
    
    function csvParse(inputString) {
       var outputArray = [];
       var inputArray = dumbComaSplit(inputString);
       for (var i =0; i < inputArray.length; i++) {
         if (!Number.isNaN(+inputArray[i])) {
           outputArray.push(+inputArray[i]);
       } else {
         outputArray.push(inputArray[i].replace(/['"]+/g,'').trim());
       }
       }
       return outputArray;
    };