2012-10-27 127 views
0

我有数据阵列这样自定义排序在JavaScript

data = [1,2,3,4,5,6,7,8,9]; 

我想给出结果这样,实施例1 + 3 = 4,4 + 3 = 7,ECT

data = [1,4,7,2,5,8,3,6,9]; 

我使用data.sort(function(x,y) { return x % 3});但没有发生。

或其他建议? 这是我的jsfiddle http://jsfiddle.net/viyancs/Yt78J/3/

+0

排序功能甚至没有考虑'y' –

+0

是的,我仍然理解排序功能.. – viyancs

+0

我的意思是1 +3 = 4 – viyancs

回答

2

您需要返回要么0-1+1指示两个项目传递给排序函数的期望的顺序。

var data = [ ... ]; 

data.sort(function (a, b) { 
    // if the value of modulo 3 of A is lower than of B, 
    // A should go first. 
    if (a % 3 < b % 3) return -1; 

    // if the value of modulo 3 of A is greater than of B, 
    // B should go first. 
    if (a % 3 > b % 3) return +1; 

    // if the value of modulo 3 is the same for both A and B 
    // the order should be figured out out of the items themself 
    if (a < b) return -1; // A should go first 
    if (a > b) return +1; // B should go first 

    return 0; // order should be preserved, will never happen for your values 
}); 
+0

gotcha,我从你的代码imageination ..谢谢... :) – viyancs

+0

哦,你说得对。 –

1

经过一点研究,我得出结论:你的例子是错误的,或者你解释的是错误的。

这里是什么,我相信将是正确的解决方案,如果我们假设INTELL的运算(其中分立后提醒保留符号):

var data = [1, 2, 3, 4, 5, 6, 7, 8, 9]; 

function mod3Sort(a, b) { 
    "use strict"; 
    var dif = a - b; 
    if (dif % 3) return a % 3 - b % 3; 
    return dif; 
} 
data.sort(mod3Sort); 

注意结果是如何从你的建议应该是不同的,究竟它是:

[3, 6, 9, 1, 4, 7, 2, 5, 8] 

这是因为数字首先被提醒分组,然后由大于关系。换句话说,首先是数字,提醒0,下一个跟随数字,提醒1,最后一组是提醒2.你拥有它的方式是:第一组是那些提醒1,第二组是那些有提醒2,最后一组是提醒0的人。因此,你需要更好地解释自己,或者纠正你的例子。