Parse CSV text into objects

“CSV reader”, a Black belt challenge from the CurlyScript Dojo. It uses what Junior Year: Modules, Node.js & npm: Working Like a Pro teaches, and 3 tests check your answer.

The challenge

Write parseCsv(text). The first line holds the column names; each following line is a record. Return an array of objects. Ignore empty lines. All values stay as strings.

Example
parseCsv("name,town\nMia,Paris\nOmar,Oslo")
// [{ name: "Mia", town: "Paris" }, { name: "Omar", town: "Oslo" }]

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • parseCsv("name,town\nMia,Paris\nOmar,Oslo") gives [{ name: "Mia", town: "Paris" }, { name: "Omar", town: "Oslo" }]
  • Empty lines are ignored: parseCsv("a,b\n1,2\n\n") gives [{ a: "1", b: "2" }]
  • parseCsv("x") gives []

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

text.split("\n") gives the lines. filter out the empty ones.

Hint 2

Destructure the header: const [header, ...rows] = lines;

Hint 3

Object.fromEntries(keys.map((k, i) => [k, values[i]])) builds an object from two arrays.

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function parseCsv(text) {
  const lines = text.split("\n").filter((line) => line.trim() !== "");
  const [header, ...rows] = lines;
  const keys = header.split(",");
  return rows.map((row) => {
    const values = row.split(",");
    return Object.fromEntries(keys.map((k, i) => [k, values[i]]));
  });
}

Learn what you need

This exercise uses what Junior Year: Modules, Node.js & npm: Working Like a Pro teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning