Home > Net >  How to properly split CSV using Javascript
How to properly split CSV using Javascript

Time:03-01

My csv file is

    1234567,AB,Client,S12345J,111 ABCD ABCEDE ADDRESS
    1234567,BC,Client,S12345J,111 ABCD ABCEDE ADDRESS
    1234567,CD,Client,S12345J,11 ABCD ABCEDE ADDRESS
    1234567,DF,Client,S12345J,856 ABCD ABCEDE ADDRESS

I have problem while using split on an CSV.... the regex command I use is /(.?,.?),.*/

        if (typeof (FileReader) != "undefined") { 
        var Allvalues = new FileReader();
        Allvalues.readAsText($("#fileUpload")[0].files[0]);
        Allvalues.onload = (f) => {
            this.splitted = f.target.result.split(/(.*?,.*?),.*/);
                                  }

I was expecting an array

          ["1234567,AB","1234567,BC"]

like

          0[] = "1234567,AB"
          1[] = "1234567,BC"

but I am getting

          ["", "1234567,AB", " ","1234567,BC",...]

like

          0[] = ""
          1[] = "1234567,AB"
          2[] = ""
          4[] = "1234567,BC"

can anyone help is rectifying it...Thanks in advance

CodePudding user response:

If no comma will ever be in the data like "111, ABCD ABCEDE, ADDRESS"

then you can split and destruct on comma and do a reduce to get unique values

const csv = `1234567,AB,Client,S12345J,111 ABCD ABCEDE ADDRESS
1234567,BC,Client,S12345J,111 ABCD ABCEDE ADDRESS
1234567,AB,Client,S12345J,11 ABCD ABCEDE ADDRESS
1234567,DF,Client,S12345J,856 ABCD ABCEDE ADDRESS`

const res = csv.split(/\n/).reduce((acc,line) => {
  const [a,b,c,d,e] = line.split(/,/)
  if (!acc.find(arr => arr[0] === a && arr[1] === b)) acc.push([a, b])
  return acc
},[])

console.log(res)

Older JS

var csv = "1234567,AB,Client,S12345J,111 ABCD ABCEDE ADDRESS\n1234567,BC,Client,S12345J,111 ABCD ABCEDE ADDRESS\n1234567,AB,Client,S12345J,11 ABCD ABCEDE ADDRESS\n1234567,DF,Client,S12345J,856 ABCD ABCEDE ADDRESS";

var lines = csv.split(/\n/)
var res = []
for (var i=0;i<lines.length;i  ) {
  var arr = lines[i].split(/,/);
  var found = false
  for (var j=0;j<res.length; j  ) {
    if (res[j][0] === arr[0] && res[j][1] === arr[1]) {
      found = true;
      break;
    }
  }
  if (!found) res.push([arr[0], arr[1]])
}

console.log(res)

  • Related