Javascript自定义排序功能

时间:2018-01-30 11:15:45

标签: javascript jquery

我有一个自定义排序功能,如下所示

sortArrayBy: function(a, b, sortKey) {
    if (a[sortKey] < b[sortKey])
        return -1;
    if (a[sortKey] > b[sortKey])
        return 1;
    return 0;
},

如何更新它以根据附加参数isAscending(可以为true / false)动态排序/切换

因此函数签名看起来像

sortArrayBy: function(a, b, sortKey, isAscending) {

}

2 个答案:

答案 0 :(得分:5)

isAscending转换为1(升序)或-1(降序)

sortArrayBy: function(a, b, sortKey, isAscending) {
   return (a[sortKey] - b[sortKey]) * (isAscending ? 1 : -1);
}

<强>演示

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

修改

包括字符串比较

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

答案 1 :(得分:1)

轻松一个

eval()