Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

javascript - Sort an integer array, keeping first in place

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] 
  • keeping array[0] in place
  • with the next highest integer(s) following (if there are any)
  • then ascending from the lowest integer
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...