Search code examples
javascriptarraysnormalize

alernative to normalize() for sorting an array


I have an application that is sorting an array of speakers alphabetically. Some of the names of the speakers have special characters such as "Álvaro" on the first letter.

I was able to get it to work using normalize() as illustrated below

filteredData = filteredData.sort((a,b)=>{

        a = a.name.normalize('NFD')
        b = b.name.normalize('NFD')

        if(a < b){
            return -1
        }
        if(a >b){
            return 1
        }
        return 0
    }) 

However, much to my dismay i found out that IE is not reeading that properly. I had the same issue with .find() but i found a simple polyfill that fixed it very quickly. I haven't found a good polyfill i can just plug in to fix normalize().

Could i use a alternative to normalize() or does anyone know of a legit good polyfill for this method?


Solution

  • localeCompare is typically used for sorting strings. It has lots of options for localization or sorting numbers and it's supported by IE:

    let names = [
        'Álvaro',
        'AArdvark',
        'Mark',
        'Álmaro',
        "Alvaro",
        "Áavaro"
    ]
    console.log(names.sort((a, b) => a.localeCompare(b)))