[英]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:为了对数组进行排序,我使用了这样的 sort 函数:
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
:在将它们与
localeCompare
进行比较之前,您可以在两个名称上调用String#normalize
:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.