How would I sort arrays as follows:
[10, 7, 12, 3, 5, 6] --> [10, 12, 3, 5, 6, 7]
[12, 8, 5, 9, 6, 10] --> [12, 5, 6, 8, 9, 10]
An easy solution could be to sort the entire array and then partition the resulting array on basis of your initial first element.
I.e.
[10, 7, 12, 3]
to [3, 7, 10, 12]
>= 10
and < 10
: [10, 12]
and [3, 7]
[10, 12, 3, 7]
Sample implementation without polish:
function customSort(input) {
var firstElem = input[0];
var sortedInput = input.sort(function(a, b) { return a-b; });
var firstElemPos = sortedInput.indexOf(firstElem);
var greaterEqualsFirstElem = sortedInput.splice(firstElemPos);
var lessThanFirstElem = sortedInput.splice(0, firstElemPos);
return greaterEqualsFirstElem.concat(lessThanFirstElem);
}
console.log(customSort([10, 7, 12, 3, 5, 6]));
console.log(customSort([12, 8, 5, 9, 6, 10]));
console.log(customSort([12, 8, 5, 9, 12, 6, 10]));
console.log(customSort([12]));
console.log(customSort([]));