0

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;
}
2
  • What does the gap mean here ? Commented Mar 10, 2017 at 19:42
  • There's a sort order and I can't have the numbers skipping numbers in the sortOrder property. So if I have two objects in the array: p[0].sortOrder=1 and p[1].sortOrder=3, it needs to convert the 3 to a 2 so there's no number gaps. Commented Mar 10, 2017 at 20:02

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

2

An ES6 version which first uses a Set to get the unique items and then a Map to map the original values with the indices of the set:

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

let map = new Map([...new Set(p.map(o=>o.sortOrder))].sort((a,b)=>a-b).map((sO,ind)=>[sO,ind+1]));
for(let o of p)
	o.sortOrder = map.get(o.sortOrder);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.