Reputation: 101
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")));
Upvotes: 0
Views: 771
Reputation: 329
You could use localeCompare()
(docs) to compare the properties if they are strings.
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()
.
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;
}
}
}
Upvotes: 1