sort alphabetically angular 6 code example

Example: Order and grouping alphabetically

const contacts= [{
    name: 'Aa',
    company: 'Company name',
    locaton: 'Location',
    other: 'other'
}, {
    name: 'Aab'
}, {
    name: 'Bb'
}, {
    name: 'Cc'
}, {
    name: 'Ccc'
}, {
    name: 'Fff'
}, {
    name: 'Faa'
}, {
    name: 'Ba'
}];

const sorted = contacts.sort((a, b) => a.name > b.name ? 1 : -1);

const grouped = sorted.reduce((groups, contact) => {
    const letter = contact.name.charAt(0);

    groups[letter] = groups[letter] || [];
    groups[letter].push(contact);

    return groups;
}, {});

const result = Object.keys(grouped).map(key => ({key, contacts: grouped[key]}));

console.log(result);

Tags:

Misc Example