How to properly sort JavaScript array with numeric values

I’m working with an array that contains strings with numbers at the end:

var itemList = ['item1', 'item6', 'item7', 'item11', 'item12'];

When I use the default itemList.sort() method, it doesn’t sort the numbers correctly. Instead of getting a logical order, I get this weird result:

itemList:
['item1', 'item11', 'item12', 'item6', 'item7']

The problem is that JavaScript treats these as strings, so it sorts them alphabetically instead of numerically. This means ‘item11’ comes before ‘item6’ because ‘1’ comes before ‘6’ in string comparison. I need a way to sort these items so the numbers are in the right order. What’s the best approach to handle this kind of natural sorting in JavaScript?

Had the same issue recently with a project that needed to sort strings with numeric endings. I used a comparator that pulls out the numbers for comparison:

itemList.sort((a, b) => {
    const numA = parseInt(a.replace(/^\D+/, ''));
    const numB = parseInt(b.replace(/^\D+/, ''));
    return numA - numB;
});

This handles the numeric suffixes properly and sorts them correctly. Just watch out for strings that don’t have numbers - you’ll want to handle those edge cases.

just use localeCompare with the numeric option - way easier than regex. itemList.sort((a, b) => a.localeCompare(b, undefined, {numeric: true})); handles mixed text/numbers automatically, no parsing needed.

The localeCompare approach works great, but if you want more control over sorting, split the string and handle each part separately:

itemList.sort((a, b) => {
    const aParts = a.match(/(\D+)(\d+)/);
    const bParts = b.match(/(\D+)(\d+)/);
    
    if (aParts[1] !== bParts[1]) {
        return aParts[1].localeCompare(bParts[1]);
    }
    return parseInt(aParts[2]) - parseInt(bParts[2]);
});

This sorts by text first, then numbers. Super helpful with mixed prefixes like ‘item1’, ‘data5’, ‘item2’. The regex gives you flexibility for trickier sorting later.