Sorting complex objects

sort(compareFn) where compareFn is the function that takes two arguments and compares a with b. In this case, use the localeCompare function to determine the sort order of strings based on the current, or specified locale:

.sort((a, b) => a.text.localeCompare(b.text))
fetch(url).then(response => response.json()).then((options: Array<{ value: string; text: string, optgroup: string }>) => {
    const optgroups = new Set<string>();
    options.forEach(o => optgroups.add(o.optgroup));
    const sortedGroups = [...optgroups].map(x => x).sort();
    //console.log(sortedGroups);
    const container = document.createElement('div');
    sortedGroups.forEach(group => {
        // Create heading for the group
        const heading = document.createElement('h5');
        heading.textContent = group;
        container.appendChild(heading);
        
        // Get all items in this group and sort them by text
        const groupItems = options
            .filter(o => o.optgroup === group)
            .sort((a, b) => a.text.localeCompare(b.text));
        
        // Create list for the items
        const list = document.createElement('ul');
        
        // Add each item to the list
        groupItems.forEach(item => {
            const listItem = document.createElement('li');
            listItem.textContent = item.text;
            // You could also store the value as a data attribute if needed
            listItem.dataset.value = item.value;
            list.appendChild(listItem);
        });
        
        container.appendChild(list);
        });

        // add container somewhere

});
Last updated: 3/27/2025 4:41:08 PM

Latest Updates

© 0 - 2025 - Mike Brind.
All rights reserved.
Contact me at Mike dot Brind at Outlook.com