Answers for "Order and grouping alphabetically"

0

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);
Posted by: Guest on June-27-2020

Code answers related to "Order and grouping alphabetically"

Browse Popular Code Answers by Language