Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
How to properly split CSV using Javascript

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!