我有一个关于如何按字母顺序排列这个对象数组的问题,知道数组的一些元素是小写的,而其他元素有特殊字符。该数组是: 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 }我必须用这个形状按字母顺序排序: 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 }但结果如下: 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 }为了对数组进行排序,我使用了这样的排序函数:orderByName(){ return this.products.sort((a,b) => a.name - b.name); return a.name - b.name;}我已经尝试了很多事情来让它与一些带有特殊字符的单词和一些小写字母一起排序。有谁知道任何解决方案?
1 回答
MM们
TA贡献1886条经验 获得超2个赞
String#normalize在将它们与以下内容进行比较之前,您可以调用这两个名称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);
添加回答
举报
0/150
提交
取消