Skip to content

Instantly share code, notes, and snippets.

@DanielKucal
Created April 3, 2018 21:25
Show Gist options
  • Save DanielKucal/176b6f0edc339ac410161f36c91683be to your computer and use it in GitHub Desktop.
Save DanielKucal/176b6f0edc339ac410161f36c91683be to your computer and use it in GitHub Desktop.
Sort input from CSV file by header in TypeScript
export class Challenge {
public static sortCsvColumns (csv_data: string): string {
const rows = csv_data.split('\n').map(row => row.split(','));
const data: CsvData = {};
for (const row of rows) {
for (let i = 0; i < row.length; i++) {
const header = rows[0][i].toLowerCase();
if (!data[header]) {
data[header] = [];
} else {
data[header].push(row[i]);
}
}
}
const headers = Object.keys(data)
.map(key => key.toLowerCase())
.sort(Challenge.compare);
let values: Array<Array<string>> = [];
headers.forEach(header => {
values.push(data[header]);
});
values = values[0].map((col, i) => values.map(row => row[i])); // inversion
return [rows[0].sort(Challenge.compare)]
.concat(values).map(r => r.join(',')).join('\n');
}
private static compare(a: string, b: string) {
return a.localeCompare(b);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment