Ana García
Ana García

Reputation: 23

How can I sort this array of objects alphabetically in node js?

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?

Upvotes: 1

Views: 3998

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370789

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);

Upvotes: 4

Related Questions