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);
添加回答
举报