Created
April 3, 2018 21:25
-
-
Save DanielKucal/176b6f0edc339ac410161f36c91683be to your computer and use it in GitHub Desktop.
Sort input from CSV file by header in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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