0

我有这样的数据数组

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

我想给出这样的结果,例如 1 + 3 = 4、4 + 3 = 7 等

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/

4

2 回答 2

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
});
于 2012-10-27T11:21:13.407 回答
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 的人。因此,您需要更好地解释自己,或者纠正您的示例。

于 2012-10-27T23:02:16.027 回答