📌  相关文章
📜  按字母顺序排序和分组 - 无论代码示例

📅  最后修改于: 2022-03-11 14:58:49.726000             🧑  作者: Mango

代码示例1
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);