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]
You could save the value of the first element and use it in a condition for the first sorting delta. Then sort by the standard delta.
How it works (the sort order is from Edge)
condition numerical sortFn a b delta delta result comment ----- ----- --------- --------- --------- ----------------- 7 10* 1 1 different section 12* 7 -1 -1 different section 12* 10* 0 2 2 same section 12* 7 -1 -1 same section 3 7 0 -4 -4 same section 3 12* 1 1 different section 3 7 0 -4 -4 same section 5 7 0 -2 -2 same section 5 12* 1 1 different section 5 3 0 2 2 same section 5 7 0 -2 -2 same section 6 7 0 -1 -1 same section 6 3 0 3 3 same section 6 5 0 1 1 same section 6 7 0 -1 -1 same section * denotes elements who should be in the first sectionElements of different section means one of the elements goes into the first and the other into the second section, the value is taken by the delta of the condition.
Elements of the same section means, both elements belongs to the same section. For sorting the delta of the values is returned.
function sort(array) {
var first = array[0];
array.sort(function (a, b) {
return (a < first) - (b < first) || a - b;
});
return array;
}
console.log(sort([10, 7, 12, 3, 5, 6]));
console.log(sort([12, 8, 5, 9, 6, 10]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
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([]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With