而排序小写字母和大写字母是分开处理的



排序字符串字段时

  • 如果字段为空,那么它应该在desc中位于顶部,在asc中位于底部(这很好(
  • For Integer行为很好(它考虑空/未定义的值并进行排序(

唯一的问题是"区分大小写">

  • 它应该将"玫瑰色"one_answers"玫瑰"视为相同的,并依次显示它们

function dynamicsort(property,order) {
var sort_order = 1;
if(order === "desc"){
sort_order = -1;
}
return function (a, b){
//check if one of the property is undefined
if(a[property] == null){
return 1 * sort_order;
}
if(b[property] == null){
return -1 * sort_order;
}
// a should come before b in the sorted order
if(a[property] < b[property]){
return -1 * sort_order;
// a should come after b in the sorted order
}else if(a[property] > b[property]){
return 1 * sort_order;
// a and b are the same
}else{
return 0 * sort_order;
}
}
}
let employees = [
{
firstName: 'John11',
age: 27,
joinedDate: 'December 15, 2017'
},
{
firstName: 'john22',
lastName: 'rosy',
age: 44,
joinedDate: 'December 15, 2017'
},
{
firstName: 'SSS',
lastName: 'SSSS',
age: 111,
joinedDate: 'January 15, 2019'
},
{
firstName: 'Ana',
lastName: 'Rosy',
age: 25,
joinedDate: 'January 15, 2019'
},
{
firstName: 'Zion',
lastName: 'Albert',
age: 30,
joinedDate: 'February 15, 2011'
},
{
firstName: 'ben',
lastName: 'Doe',
joinedDate: 'December 15, 2017'
},
];
console.log("Object to be sorted");
console.log(employees);
console.log("Sorting based on the lastName property")
console.log(employees.sort(dynamicsort("lastName","desc")));
console.log("Sorting based on the lastName property")
console.log(employees.sort(dynamicsort("lastName","asc")));

如果属性是字符串,则可以使用localeCompare()(docs(来比较它们。

下面是一个基于代码的简单示例。还有其他可能的改进,但我不想对您的原始代码做太多更改,所以我只是展示了使用localeCompare()的一种方法。

function dynamicsort(property,order) {
var sort_order = 1;
if(order === "desc"){
sort_order = -1;
}
return function (a, b){
//check if one of the property is undefined
if(a[property] == null){
return 1 * sort_order;
}
if(b[property] == null){
return -1 * sort_order;
}
// if both properties are strings use localeCompare
if (typeof a[property] === "string" && typeof b[property] === "string") {
return a[property].localeCompare(b[property]) * sort_order;
}
// a should come before b in the sorted order
if(a[property] < b[property]){
return -1 * sort_order;
// a should come after b in the sorted order
}else if(a[property] > b[property]){
return 1 * sort_order;
// a and b are the same
}else{
return 0 * sort_order;
}
}
}

在排序前将两个字符串都转换为小写或大写。

最新更新