Javascript js中的排序数组

Javascript js中的排序数组,javascript,arrays,sorting,Javascript,Arrays,Sorting,我有一个目标: var Data = [{ item_id:1, name:'John', date:1262293200000, votes:1 }, { item_id:2, name:'Nick', date:1313784000000, votes:2 },{ item_id:3, name:'Paul', date:1299186000000, votes:-3 }] 我想按项目id,名

我有一个目标:

var Data = [{
    item_id:1,
    name:'John',
    date:1262293200000,
    votes:1
}, {
    item_id:2,
    name:'Nick',
    date:1313784000000,
    votes:2
},{ 
    item_id:3,
    name:'Paul',
    date:1299186000000,
    votes:-3
}]
我想按
项目id
名称
日期
投票数
对其进行排序Ascdesc。为此,我使用此功能:

function dynamicSort(property) { 
    return function (a,b) { 
        return (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0; }}

Array.prototype.sortBy = function(property) { return this.sort(dynamicSort(property)) }
Array.prototype.reverseBy = function(property) { return this.reverse(dynamicSort(property)) }
function dynamicSortReverse(property)
{
  var innerFunc = dynamicSort(property);
  return function(a, b) { return -1 * innerFunc(a, b); };
}
Array.prototype.reverseBy = function(property) { return this.sort(dynamicSortReverse(property)); };
结果将是错误的,但如果我排序,然后再次
reverseBy
它将是正确的排序。 另外,如果我调用
reverseBy
,然后
sortBy
排序
sortBy
将是正确的


可以修复吗?

对于接受函数作为参数的数组,没有反向函数。
你应该试试:

 Array.prototype.reverseBy = function(property) {
    return this.sortBy(dynamicSort(property)).reverse()
 }
也许你会用? 在jLinq中,排序看起来:

var result = jlinq.from(Data).sort("-votes").select();
console.log(result);
不接受任何参数。它不会对数组进行排序,只会反转其当前顺序。因此,您可以先对列表进行排序(请注意,
Array.reverse()
Array.sort
在不创建新数组的情况下就地修改数组):

或者使用反向排序功能:

function dynamicSort(property) { 
    return function (a,b) { 
        return (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0; }}

Array.prototype.sortBy = function(property) { return this.sort(dynamicSort(property)) }
Array.prototype.reverseBy = function(property) { return this.reverse(dynamicSort(property)) }
function dynamicSortReverse(property)
{
  var innerFunc = dynamicSort(property);
  return function(a, b) { return -1 * innerFunc(a, b); };
}
Array.prototype.reverseBy = function(property) { return this.sort(dynamicSortReverse(property)); };
第二种方法更有效

请注意,如果仅按数值属性排序,则可以简化
dynamicSort
函数:

function dynamicSort(property)
{ 
  return function (a, b)
  { 
    return a[property] - b[property];
  }
}

这也应该稍微更有效率。当然,如果您有时按字符串值排序,您仍然需要旧函数。

您错了
dynamicSort(property)
调用一次,其结果(sort函数)作为参数传递给
Array.sort()
。每次比较(顺便说一句,有
n*log(n)
用于排序的比较)都会调用该函数(并且只有该函数)。所以你的优化没有任何效果。你是对的,我想我现在想清楚还为时过早:)我将从我的帖子中删除这个。