Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Resorting and removing number gaps using javascript array

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...