2

I have the following code:

var compare = function( nodeA, nodeB ){
    return +nodeA.index - +nodeB.index;
};

var sort = function( nodes ){
    nodes.sort( compare );
};

The node has this (pseudo) structure:

{
   index: <integer>
   value: <literal>
}

And it currently sorts them the regular way, when I call the sort function, and print out the index's of each node:

0
1
2
3

How can I change my current logic to make it look like this? :

1
2
3
0 <-- 0 should be considered the biggest index
amigo21
  • 381
  • 1
  • 4
  • 18
  • Possible duplicate of [How does sort function work in JavaScript, along with compare function](http://stackoverflow.com/questions/6567941/how-does-sort-function-work-in-javascript-along-with-compare-function) – Heretic Monkey Mar 03 '17 at 16:31

4 Answers4

1

You can first sort by condition that index != 0 and then just sort by index value.

var data = [{
   index: 2,
   value: 'a'
}, {
   index: 0,
   value: 'b'
},{
   index: 3,
   value: 'c'
},{
   index: 1,
   value: 'd'
}]

var result = data.sort(function(a, b) {
  return (b.index != 0) - (a.index != 0) || (a.index - b.index)
})
console.log(result)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

You can add special handling for zeroes:

var compare = function(nodeA, nodeB) {
  // in case both sides are equal
  if (nodeA.index === nodeB.index) {
    return 0;
  }
  if (nodeA.index === 0) {
    return 1;
  }
  if (nodeB.index === 0) {
    return -1;
  }

  return +nodeA.index - +nodeB.index;
};

var data = [{
  index: 2,
  value: 'a'
}, {
  index: 0,
  value: 'b'
}, {
  index: 3,
  value: 'c'
}, {
  index: 1,
  value: 'd'
}]

data.sort(compare);

console.log(data);
JLRishe
  • 99,490
  • 19
  • 131
  • 169
0

Just change compare to:

var compare = function( nodeA, nodeB ){
    return ((+nodeA.index || Infinity) - (+nodeB.index || Infinity)) || Infinity;
};

|| operator returns the first value that is not "falsy", which is a "truthy" value, but is also the actual value. This is a EMCA5 "trick" to create default values to variables.

So explaining:

  • for nodeA.index == 0 && nodeB.index > 0 => Infinity - somevalue == Infinity
  • for nodeA.index > 0 && nodeB.index == 0 => somevalue - Infinity == -Infinity
  • for nodeA.index == 0 && nodeB.index == 0 => Infinity - Infinity == NaN in which case the || Infinity option is choosen
Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73
0

You just need to change your compare function a little bit:

var compare = function( nodeA, nodeB ){
  if (!+nodeA.index) return 1;
  if (!+nodeB.index) return -1;
  return +nodeA.index - +nodeB.index;
};
Omar Vazquez
  • 407
  • 4
  • 14