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

Categories

I'm trying to resort and then remove any gaps in the numbers for the sortOrder property in this JavaScript array.

So for example:

p[0].sortOrder = 2; 
p[1].sortOrder = 12;
p[2].sortOrder = 4;
p[3].sortOrder = 8;
p[4].sortOrder = 6; 
p[5].sortOrder = 2; 
p[6].sortOrder = 8;   

Should be output to:

p[0].sortOrder = 1; //used to be 2
p[1].sortOrder = 5; //used to be 12
p[2].sortOrder = 2; //used to be 4
p[3].sortOrder = 4; //used to be 8
p[4].sortOrder = 3; //used to be 6 
p[5].sortOrder = 1; //used to be 2
p[6].sortOrder = 4; //used to be 8   

Here's the function it should run in. I can't wrap my head around the elimination of the gaps in the numbers.

function restackSortOrder(p) {

    //Remove any gaps in numbers here while still retaining any duplicate numbers (which should stay grouped together).

    return p;
}
See Question&Answers more detail:os

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

1 Answer

Here's a solution, with explanation in the comments:

function resortStackorder(p) {
  var match = p.map(function(e) {                   //create array of sortOrder values
                return e.sortOrder;
              })
               .sort(function(a, b) {return a - b}) //sort the array numerically
               .filter(function(e, idx, array) {    //filter out duplicates
                 return e !== array[idx - 1];
               });

  p.forEach(function(e) {  //look up sortOrder's position in the match array
    e.sortOrder = match.indexOf(e.sortOrder) + 1;
  });
} //resortStackorder

var p = [
  {sortOrder: 2},
  {sortOrder: 12},
  {sortOrder: 4},
  {sortOrder: 8},
  {sortOrder: 6},
  {sortOrder: 2},
  {sortOrder: 8}
];

resortStackorder(p);

console.log(JSON.stringify(p));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...