Reputation: 50742
I have a custom sort function defined as below
sortArrayBy: function(a, b, sortKey) {
if (a[sortKey] < b[sortKey])
return -1;
if (a[sortKey] > b[sortKey])
return 1;
return 0;
},
How can I update it to dynamically sort/toggle based on an additional parameter isAscending which can be true/false
So the function signature would look like
sortArrayBy: function(a, b, sortKey, isAscending) {
}
Upvotes: 1
Views: 106
Reputation: 18610
easy one
sortArrayBy: function(a, b, sortKey , isAscending) {
if (parseFloat(a[sortKey]) < parseFloat(b[sortKey]))
return isAscending ? -1 : 1;
if (parseFloat(a[sortKey]) > parseFloat(b[sortKey]))
return isAscending ? 1 : -1;
return 0;
},
Upvotes: 1
Reputation: 68413
Convert isAscending
to a 1
(for ascending) or -1
(for descending)
sortArrayBy: function(a, b, sortKey, isAscending) {
return (a[sortKey] - b[sortKey]) * (isAscending ? 1 : -1);
}
Demo
function sortArrayBy(arr, sortKey, isAscending) {
return arr.sort( ( a, b ) => (a[sortKey] - b[sortKey]) * (isAscending ? 1 : -1) );
}
var arr = [
{ a : 1, b: 2 },
{ a : 4, b: 6 },
{ a : 3, b: 4 },
{ a : 12, b: 1 },
{ a : 5, b: 23 },
];
console.log( sortArrayBy( arr, "a", true ) );
console.log( sortArrayBy( arr, "a", false ) );
Edit
Including string comparison as well
function sortArrayBy(arr, type, sortKey, isAscending) {
if ( type == "string" )
{
return arr.sort( ( a, b ) => a[sortKey].localeCompare(b[sortKey]) * (isAscending ? 1 : -1) );
}
return arr.sort( ( a, b ) => (a[sortKey] - b[sortKey]) * (isAscending ? 1 : -1) );
}
function sortArrayBy(arr, type, sortKey, isAscending) {
if ( type == "string" )
{
return arr.sort( ( a, b ) => a[sortKey].localeCompare(b[sortKey]) * (isAscending ? 1 : -1) );
}
return arr.sort( ( a, b ) => (a[sortKey] - b[sortKey]) * (isAscending ? 1 : -1) );
}
var arr = [
{ a : 1, b: "32" },
{ a : 4, b: "w6" },
{ a : 3, b: "s4" },
{ a : 12, b: "v1" },
{ a : 5, b: "2s3" },
];
console.log( sortArrayBy( arr, "", "a", true ) );
console.log( sortArrayBy( arr, "", "a", false ) );
console.log( sortArrayBy( arr, "string", "b", true ) );
console.log( sortArrayBy( arr, "string", "b", false ) );
Upvotes: 5