viyancs
viyancs

Reputation: 2339

Custom Sorting in JavaScript

i have data array like this

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

i want to giving result like this, example 1 + 3 = 4, 4 + 3 = 7,ect

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

i'm using data.sort(function(x,y) { return x % 3}); but nothing happen.

or any another suggestion ? this is my jsfiddle http://jsfiddle.net/viyancs/Yt78J/3/

Upvotes: 0

Views: 149

Answers (2)

user797257
user797257

Reputation:

After a little bit of research, I came to conclusion that your example is wrong, or what you explained is wrong.

Here's what I believe would be the correct solution, if we assume Intell's arithmetic (where reminder retains the sign after division):

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

Notice how the result is different from what you suggested it should be, exactly it is:

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

This is so because numbers are first grouped by reminder, then by greater then relation. In other words, first are the numbers, with reminder of 0, the next follow the numbers, with reminder 1, the last group is the reminder of 2. The way you have it is: the first group are those who have reminder 1, second group are those who have the reminder 2 and the last group are those who have the reminder 0. Hence, you need to either explain yourself better, or correct your example.

Upvotes: 1

J. K.
J. K.

Reputation: 8368

You need to return either 0, -1 or +1 indicating the desired order of the two items passed to the sorting function.

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

Upvotes: 2

Related Questions