JavaScript Sort Stack Coding Challenge A coding challenge to write a function sortStack that receives a stack of integers into ascending order (with largest integers on top) and returns another stack with sorted integers. At most one additional stack may be used to hold items; no other data structures may be used to copy or hold the elements.

Stack Class:

class Stack {
  constructor() {
    this.storage = [];
  }

  push(item) {
    this.storage.push(item);
  }

  pop() {
    return this.storage.pop();
  }

  peek() {
    return this.storage[this.storage.length-1];
  }

  isEmpty() {
    return this.storage.length === 0;
  }

  printContents() {
    this.storage.forEach(elem =&gt; console.log(elem));
  }
}


Stack:

const s = new Stack();
s.push(4);
s.push(10);
s.push(8);
s.push(5);
s.push(1);
s.push(6);


My solution: 

const sortStack = (stack) =&gt; {
  sorted = new Stack();
  while (stack.storage.length) {
    tmp = stack.pop();  
    if (tmp &gt;= sorted.peek()) {
      sorted.push(tmp);
    } else {
      while (tmp &lt; sorted.peek()) {
        stack.push(sorted.pop());
      }
      sorted.push(tmp);
    }
  }
  return sorted;
}

sortedStack = sortStack(s);
sortedStack.printContents(); // correctly outputs 1, 4, 5, 6, 8, 10


This iterative solution returns the correct output on multiple test cases, and there are no missing edge cases or other logical flaws that I can see, however I don't like the nested while-loop. 

I want to keep the solution iterative, so how could I go about not having to use the nested while-loop?
You have access to the stack array directly so you can copy the unsorted stack it to a new stack and sort it in place using Array.sort

"use strict";
function sortStack(stack) {
    const sorted = new Stack();
    while (!stack.isEmpty()) { sorted.push(stack.pop()) }
    sorted.storage.sort((a, b) =&gt; a - b);
    return sorted;
}


or

"use strict";
function sortStack(stack) {
    const sorted = new Stack();
    sorted.storage = [...stack.storage].sort((a, b) =&gt; a - b);
    return sorted;
}


If they did not want you to access the storage array directly they would have protected it in closure. (well if that crossed their minds)

BTW your should always add "use strict" to the top of your javascript code as you have neglected to declare any of your variables, making them all global and setting your self up for some horror bugs.

The use strict directive will not let you use undeclared variable.