繁星淼淼
2023-04-14 15:17:37
我有一個關(guān)于如何按字母順序排列這個對象數(shù)組的問題,知道數(shù)組的一些元素是小寫的,而其他元素有特殊字符。該數(shù)組是: 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 }但結(jié)果如下: 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 }為了對數(shù)組進行排序,我使用了這樣的排序函數(shù):orderByName(){ return this.products.sort((a,b) => a.name - b.name); return a.name - b.name;}我已經(jīng)嘗試了很多事情來讓它與一些帶有特殊字符的單詞和一些小寫字母一起排序。有誰知道任何解決方案?
1 回答

MM們
TA貢獻1886條經(jīng)驗 獲得超2個贊
String#normalize在將它們與以下內(nèi)容進行比較之前,您可以調(diào)用這兩個名稱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
提交
取消