jmk*_*jmk 3 javascript sorting
我如何按如下方式对数组进行排序:
[10, 7, 12, 3, 5, 6] --> [10, 12, 3, 5, 6, 7]
[12, 8, 5, 9, 6, 10] --> [12, 5, 6, 8, 9, 10]
Run Code Online (Sandbox Code Playgroud)
您可以保存第一个元素的值,并在第一个排序增量的条件中使用它.然后按标准增量排序.
工作原理(排序顺序来自Edge)
Run Code Online (Sandbox Code Playgroud)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 section的元件不同部分装置的要素之一进入所述第一和其他进入第二部分,该值被取由条件的Δ.
所述的元件相同的部分装置,这两个元件属于相同部分.对于排序,返回值的增量.
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]));Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)