简体   繁体   中英

Javascript Custom sort function

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) {

}

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 ) ); 

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;
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM