Untitled

 avatar
unknown
plain_text
a year ago
591 B
2
Indexable
function groupTransactions(transactions) {
    // Count the occurrences of each item using a Map
    const counts = new Map();
    for (const item of transactions) {
        counts.set(item, (counts.get(item) || 0) + 1);
    }

    // Convert the Map to an array and sort it
    return Array.from(counts)
        .sort((a, b) => {
            // Sort by count in descending order, then by name in ascending order
            return b[1] - a[1] || a[0].localeCompare(b[0]);
        })
        // Map to the required format: "name count"
        .map(([name, count]) => `${name} ${count}`);
}
Leave a Comment