简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM