Last updated
Sorting CSV Data
CSV sorting reorders rows based on one or more column values. Sorting can be ascending or descending, and can handle different data types: text (alphabetical), numbers (numeric), and dates (chronological). Multi-column sorting applies the first sort key, then uses subsequent keys to break ties.
CSV Sort in JavaScript
JavaScript
function sortCsv(csvText, sortKeys) {
// sortKeys: [{ column: 'age', direction: 'asc', type: 'number' }]
const lines = csvText.trim().split('
');
const headers = lines[0].split(',').map(h => h.trim());
const rows = lines.slice(1).map(l => l.split(','));
rows.sort((a, b) => {
for (const { column, direction, type } of sortKeys) {
const idx = headers.indexOf(column);
if (idx === -1) continue;
let va = a[idx]?.trim() ?? '';
let vb = b[idx]?.trim() ?? '';
let cmp;
if (type === 'number') {
cmp = parseFloat(va) - parseFloat(vb);
} else if (type === 'date') {
cmp = new Date(va) - new Date(vb);
} else {
cmp = va.localeCompare(vb);
}
if (cmp !== 0) return direction === 'desc' ? -cmp : cmp;
}
return 0;
});
return [lines[0], ...rows.map(r => r.join(','))].join('
');
}
Sorting Best Practices
- Always preserve the header row — sort only data rows.
- Handle empty cells consistently — sort them to the end or beginning.
- Use locale-aware string comparison (
localeCompare) for international text. - For large files (100K+ rows), use a streaming approach to avoid memory issues.