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]
Have a look at below snippet.
It is really simple. Just remove first element from the arrary into new array.
Sort rest of the array and check if max of this array is greater than first element.
If yes, then push it into to result arrary. Otherwise concat rest of the array with result array
var input1 = [10, 7, 12, 3, 5, 6];
var expected1 = [10, 12, 3, 5, 6, 7];
var input2 = [12, 8, 5, 9, 6, 10];
var expected2 = [12, 5, 6, 8, 9, 10];
function customSort(aInput) {
var aResult = [aInput.shift()];
aInput = aInput.sort(function(a, b) { return a - b;});
if (aInput[aInput.length - 1] > aResult[0]) {
var iMax = aInput.pop();
aResult.push(iMax);
}
aResult = aResult.concat(aInput);
return aResult;
}
console.log("Expected: ", expected1.toString());
console.log("Sorted: ", customSort(input1).toString());
console.log("Expected: ", expected2.toString());
console.log("Sorted: ", customSort(input2).toString());