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?

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.