LearnFrenzy
Sign in Take a free test

Destructuring · Destructuring Coding Problems · Question 6

Parse CSV rows with destructuring in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Parse CSV lines "name,department,salary,joined" into objects, converting salary to a number and the joining date into its year, skipping the header row.

Solution
main.js
const csv = `name,department,salary,joined
Asha,Engineering,85000,2021-04-12
Ravi,Sales,62000,2019-08-01
Meera,Engineering,91000,2023-01-20`;

const [, ...lines] = csv.split("\n");                     // skip the header
const employees = lines.map((line) => {
  const [name, department, salary, joined] = line.split(",");
  const [year] = joined.split("-");
  return { name, department, salary: Number(salary), year: Number(year) };
});

const engineering = employees.filter(({ department }) => department === "Engineering");
console.log(engineering.map(({ name, year }) => `${name} (${year})`).join(", "));
console.log("Total salary:", employees.reduce((sum, { salary }) => sum + salary, 0));

Output Verified by running it on Node.js

Asha (2021), Meera (2023)
Total salary: 238000

An empty first element skips the header; each line is split and unpacked by position; destructuring in the filter, map and reduce callbacks reads only the fields each step needs.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links