我已經嘗試了 map 和 forEach 回圈,但仍然無法按字母順序排序。不知道我在這里缺少什么。
我的陣列:
const filtData = [
[
{
gameType: "Rowing",
},
{
gameType: "Rowing",
},
{
gameType: "Rowing",
},
],
[
{
gameType: "Golf",
},
{
gameType: "Golf",
},
{
gameType: "Golf",
},
],
[
{
gameType: "Soccer",
},
{
gameType: "Soccer",
},
{
gameType: "Soccer",
},
],
[
{
gameType: "Baseball",
},
{
gameType: "Baseball",
},
{
gameType: "Baseball",
},
],
]
JS:
filtData.forEach(d => d.sort((a,b) => a.gameType - b.gameType))
console.log(filtData) /* <--fails */
const sortedData = filtData.map((d) => d.sort((a, b) => {
return a.gameType - b.gameType;
}));
console.log("sortedData", sortedData)/* <--fails */
JsFiddle: https ://jsfiddle.net/eL510oq3/
uj5u.com熱心網友回復:
幾點:
- 您是根據字串而不是數字進行排序的,因此請使用
String#localeCompare - 無需使用
forEachor.map,只需sort
const filtData = [ [ { gameType: "Rowing", }, { gameType: "Rowing", }, { gameType: "Rowing", }, ], [ { gameType: "Golf", }, { gameType: "Golf", }, { gameType: "Golf", }, ], [ { gameType: "Soccer", }, { gameType: "Soccer", }, { gameType: "Soccer", }, ], [ { gameType: "Baseball", }, { gameType: "Baseball", }, { gameType: "Baseball", }, ], ];
filtData.sort((a,b) => a[0].gameType.localeCompare(b[0].gameType))
console.log(filtData);
uj5u.com熱心網友回復:
在 ASC 排序方法 1 中對陣列物件進行排序:
let arrayConcat = filtData.reduce((preValue, curValue) => {
return preValue.concat(curValue)
}, []);
let result = arrayConcat.sort((a, b) => {
return a.gameType.localeCompare(b.gameType);
})
console.log(result);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/476031.html
標籤:javascript 数组 排序 多维数组
