Scriptdrill

Level 4: Data shaping Exercise 28 of 45 Pro

CSV text to objects

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Parse simple CSV text (no quoted fields) into an array of objects. The first non-blank line holds the headers. Lines end with `\n` or `\r\n`, and blank lines are skipped. Headers and values are trimmed of surrounding spaces and stay strings. A row with fewer values than headers gets `""` for the missing ones.

What this exercise teaches

Splitting on /\r?\n/ handles both line endings, and filtering blank lines also removes the empty string a trailing newline leaves at the end. `vals[i] ?? ""` fills in missing trailing values.

A hint if you get stuck

Split on `/\r?\n/`, drop lines that are blank after trimming, take the first line as headers, then build one object per remaining line.

This exercise is part of Pro

Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.

You create a free account first, so Pro is attached to it.

Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.

Start with the free exercises

More exercises in Data shaping