Sort an integer array, keeping first in place

前端 未结 6 814
傲寒
傲寒 2020-12-19 20:21

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] 
    <
6条回答
  •  抹茶落季
    2020-12-19 21:01

    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 section
    

    Elements 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; }

提交回复
热议问题