0

What is the problem with this array sorting?

var arr = ["Q1#2013#A", "Q1#2013#B", "Q1#2014#A", "Q1#2014#B", "Q2#2013#A", "Q2#2013#B", "Q2#2014#A", "Q2#2014#B", "Q3#2013#A", "Q3#2013#B", "Q4#2013#A", "Q4#2013#B"];
arr.sort(function(a, b) {
  var s = a.split('#'), t = b.split('#');
  var c = s.pop(), d = t.pop();
  s1 = s.reverse().join('#')+'#'+c, s2 = t.reverse().join('#')+'#'+d;
  return s1 > s2;
});

It returns the following output:

["Q2#2014#A", "Q1#2013#A", "Q1#2013#B", "Q2#2013#A", "Q2#2013#B", "Q3#2013#A", "Q3#2013#B", "Q4#2013#A", "Q4#2013#B", "Q1#2014#A", "Q1#2014#B", "Q2#2014#B"]

The ideal result should be:

["Q1#2013#A", "Q1#2013#B", "Q2#2013#A", "Q2#2013#B", "Q3#2013#A", "Q3#2013#B", "Q4#2013#A", "Q4#2013#B", "Q1#2014#A", "Q1#2014#B", "Q2#2014#A", "Q2#2014#B"]
Pulkit Mittal
  • 5,696
  • 5
  • 20
  • 27
  • You should do two things: (1) declare "s1" and "s2" properly with `var` and (2) explain how you want your array sorted. – Pointy Sep 03 '14 at 13:21
  • 2
    The callback has to return a positive value, 0 or a negative value, not a Boolean. Please have a look at the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description – Felix Kling Sep 03 '14 at 13:21
  • 1
    Thank you @Felix Kling. I think I need more coffee this evening. :) – Pulkit Mittal Sep 03 '14 at 13:24
  • I heard that helps :) – Felix Kling Sep 03 '14 at 13:26

0 Answers0