lotsoftools

Javascript Read CSV

A concise, practical guide to reading CSV files in JavaScript. This snippet presents a common yet powerful method to extract and use data stored in CSV format.

const parseCSV = (data) => {
  const lines = data.split('\n');
  return lines.map(line => line.split(','));
};

fetch('./file.csv')
.then(response => response.text())
.then(data => console.log(parseCSV(data)));

This code snippet is a simple, effective method for reading CSV data in JavaScript. First, it defines a parseCSV function. This function splits the CSV data into individual lines, then further splits each line at the comma, thus transforming the CSV data into a two-dimensional array for easy accessibility.

After defining the function, the code fetches a CSV file called 'file.csv'. Once fetched, the response is converted to text. Then the parseCSV function is applied to the textual data. The resulting two-dimensional array is logged in the console for inspection.