2 回答

TA貢獻1995條經驗 獲得超2個贊
嘿,您可以使用排序函數中的屬性簡單地對數組進行排序。
升序a[property] - b[property]
降序b[property] - a[property]
按名稱排序是將所有名稱轉換為一個數組,對它們進行排序,然后循環進行排序。這運行起來n^2
所以值得研究優化,但這會讓你越過終點線。
name
注意:此功能將不起作用undefined
。
const list = [
{
name: 'compass',
kills: 35,
assists: 312
},
{
name: 'another one',
kills: 52,
assists: 32
},
{
name: 'another anothe one',
kills: 12,
assists: 30
}
]
const sortByString = () => {
const strings = list.map(prop => prop.name).sort();
let sorted = [];
for(const idx in strings){
let currString = strings[idx];
for(const objIdx in list){
console.log(currString, list[objIdx].name)
if(list[objIdx].name === currString){
sorted.push(list[objIdx]);
}
}
}
return sorted;
}
const dynamicSortByType = (property) => {
return typeof list[0][property] === 'string' ?
sortByString() : list.sort((a,b) => a[property] - b[property])
}
console.log(dynamicSortByType('name'))

TA貢獻1831條經驗 獲得超9個贊
簡短回答:
你只是漏掉了這個詞else。
長答案:
你有一個看起來像這樣的塊
if () {
}
if () {
}
else {
}
應該是這樣的:
if () {
}
else if () {
}
else {
}
請注意else在第二個之前添加了if。如果沒有它,第二個 if-else 將運行,最后的 else 將取代第一個 的 true 情況所做的設置if。
例如,任何時候if (a[property] < b[property]) {,它實際上都會落入秒數if并else導致設置result = 0。
這是您進行了微小修復的片段:
const list = [
{
name: 'compass',
kills: 35,
assists: 312
},
{
name: 'another one',
kills: 52,
assists: 32
},
{
name: 'another anothe one',
kills: 12,
assists: 30
}
];
const sortByType = (property) => {
return function (a, b) {
let result;
if (a[property] < b[property]) {
result = -1;
}
else if (a[property] > b[property]) { /* FIXED: added `else` on this line */
result = 1;
}
else {
result = 0;
}
return result;
};
}
let newList = list.sort(sortByType('kills'));
console.log(newList);
添加回答
舉報