1

I have a question about how to order this array of objects alphabetically, knowing that some of the elements of the array are in lowercase and others have special characters.

The array is:

  Product { id: 1, name: 'TV Samsung MP45', price: 325.9, units: 8 },
  Product { id: 2, name: 'Ábaco de madera (nuevo modelo)', price: 245.95, units: 15 },
  Product { id: 3, name: 'impresora Epson', price: 55.9, units: 8 },
  Product { id: 4, name: 'USB Kingston 16GB', price: 5.95, units: 45 }

I must sort alphabetically with this shape:

   Product { id: 2, name: 'Ábaco de madera (nuevo modelo)', price: 245.95, units: 15 },
   Product { id: 3, name: 'impresora Epson', price: 55.9, units: 8 },
   Product { id: 1, name: 'TV Samsung MP45', price: 325.9, units: 8 },
   Product { id: 4, name: 'USB Kingston 16GB', price: 5.95, units: 45 }

But the result is the following:

  Product { id: 1, name: 'TV Samsung MP45', price: 325.9, units: 8 },
  Product { id: 2, name: 'Ábaco de madera (nuevo modelo)', price: 245.95, units: 15 },
  Product { id: 3, name: 'impresora Epson', price: 55.9, units: 8 },
  Product { id: 4, name: 'USB Kingston 16GB', price: 5.95, units: 45 }

To order the array, I use the sort function like this:

orderByName(){
    return this.products.sort((a,b) => a.name - b.name);
        return a.name - b.name;
}

I have tried many things to get it to order with some words with special characters and some are lowercase.

Does anyone know any solutions?

Ana García
  • 23
  • 2
  • 6
  • Does this answer your question? [Sort array by firstname (alphabetically) in Javascript](https://stackoverflow.com/questions/6712034/sort-array-by-firstname-alphabetically-in-javascript) – Owen Kelvin Oct 04 '20 at 12:57

1 Answers1

4

You can call String#normalize on both names before comparing them with localeCompare:

const arr = [
{ id: 1, name: 'TV Samsung MP45', price: 325.9, units: 8 },
{ id: 2, name: 'Ábaco de madera (nuevo modelo)', price: 245.95, units: 15 },
{ id: 3, name: 'impresora Epson', price: 55.9, units: 8 },
{ id: 4, name: 'USB Kingston 16GB', price: 5.95, units: 45 }
];

arr.sort((a, b) => a.name.normalize().localeCompare(b.name.normalize()));
console.log(arr);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320