[英]While sorting lower case and upper case letters are treated seperately
While sorting String field排序字符串字段时
Only problem is with 'Case sensitivity'唯一的问题是“区分大小写”
- It should treat 'rosy' And 'Rosy' as same and display them on after another
它应该将“玫瑰色”和“玫瑰色”视为相同,并依次显示
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")));
You could use localeCompare()
( docs ) to compare the properties if they are strings.如果它们是字符串,您可以使用
localeCompare()
( docs ) 来比较属性。
Here is a simple example based on your code.这是一个基于您的代码的简单示例。 There are other possible improvements but I don't want to change your original code too much, so I'm just showing one way you could use
localeCompare()
.还有其他可能的改进,但我不想过多地更改您的原始代码,所以我只是展示了一种可以使用
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;
}
}
}
transform both strings to lower case or uppercase before the sort.在排序之前将两个字符串都转换为小写或大写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.