Search code examples
javascriptarrayssortingstring-comparison

How sort string with spaces in javascript?


I need sort strings. But it doesn't sort correctly when it finds spaces in string. How can I make it not to sort spaces?

const array = [
        { attributes: { name: 'abcd efg' } },
        { attributes: { name: 'Übd cd' } },
        { attributes: { name: 'Ku cdf' } },
        { attributes: { name: 'äb' } },
        { attributes: { name: 'abc' } }
      ]
      array.sort((a, b) => {
        if (a.attributes.name.toUpperCase()
          .localeCompare(b.attributes.name.toUpperCase(), 'de', { sensitivity: 'base' })) { return -1 }
        if (b.attributes.name.toUpperCase()
          .localeCompare(b.attributes.name.toUpperCase(), 'de', { sensitivity: 'base' })) { return 1 }
        return 0
      })
console.log('typeof array', array)

I expect to see:

[
{ attributes: { name: 'abc' } },
{ attributes: { name: 'abcd efg' } },
{ attributes: { name: 'äb' } },
{ attributes: { name: 'Ku cdf' } },
{ attributes: { name: 'Übd cd' } }
]

Solution

  • The String.localeCompare method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order... which is the same as what Array.sort is supposed to return:

    const array = [
      { attributes: { name: "abcd efg" } },
      { attributes: { name: "Übd cd" } },
      { attributes: { name: "Ku cdf" } },
      { attributes: { name: "ab" } }
    ];
    array.sort((a, b) => a.attributes.name.toUpperCase().localeCompare(b.attributes.name.toUpperCase(), "de", { sensitivity: "base" }));
    console.log(array);