Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Say I have an array of numbers:

var foo = [20, 10, 03, 04, 02, 15, 01];

I need to sort the numbers using array.sort so the result has everything smaller than ten is after ten:

[10, 15, 20, 01, 02, 03, 04]

Is a simple .sort enough? Or will I have to store values in external arrays and then pull them in (even then i'm not sure how to do it just in the sort method)? The closest thing I could find was this example, but it's written in c# and the logic isn't really explained.

The closest logic I can think of is to splice all numbers lower than 10 and put them in another array. On sort complete, sort the new array from smallest to largest and add on the end of the initial array. However, there's no sort callback of any kind.

I'm trying to use this in conjunction with KnockoutJS' inline sort implementation, so that's why I'm trying to stick to the sort method.

share|improve this question
 
Do the small numbers need to be sorted into 1, 2, 3, 4 or can they be inverted (eg: [18, 19, 20, 5, 4, 3, 2, 1])? Does the Knockout sort give you a reference to the array as a parameter, or do you just have a and b to work with? Can you call .sort twice, chained? –  Norguard 13 hours ago
 
The smaller numbers can't be inverted, the must be from largest to smallest. Knockout allows you to chain filters, yes. @steaks method works, I'm just about to put it in a codepen. –  Ojame 12 hours ago
add comment

2 Answers

up vote 1 down vote accepted

If the two numbers we're comparing both are big numbers or both small numbers, we compare as per usual. If one of the numbers is a big number and the other a small number, we pretend like the big number is smaller than the small number.

var foo = [20, 10, 03, 04, 02, 15, 01];
foo.sort(function(a,b) {
  if ((a >= 10 && b >= 10) || (a < 10 && b < 10)) {
    return a - b;
  }
  else {
    return a >= 10 ? -1 : 1;
  }
});
console.log(foo);
// [ 10, 15, 20, 1, 2, 3, 4 ]
share|improve this answer
 
Wow, this is a really nice solution. The pretending the big number is smaller is a good trick, and one that I would have never thought of. Thanks! –  Ojame 12 hours ago
add comment
var largeNumbers = foo.filter(function (v) { return v >= 10; }).sort();
var smallNumbers = foo.filter(function (v) { return v < 10; }).sort();
var myArray = largeNumbers.concat(smallNumbers);
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.