Parse CSV String to Array
Parse CSV String to Array is a reusable JavaScript snippet. Converts a CSV (comma-separated values) string into a JavaScript array of objects using the first row as headers. The full implementation: function parseCSV(csv) { const lines = csv.trim().split('\n') const headers = lines[0].split(',').map(h => h.trim()) return lines.slice(1).map(line => { const values = line.split(',').map(v => v.trim()) return headers.reduce((obj, header, i) => { obj[header] = values[i] return obj }, {}) }) } // Usage const data = `name,age,city Alice,30,New York Bob,25,London` parseCSV(data) // [{ name: "Alice", age: "30", city: "New York" }, // { name: "Bob", age: "25", city: "London" }] This snippet uses only standard JavaScript with no dependencies, so it runs in modern browsers and Node.js alike. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.