title: How to optimize my function that takes a positive integer and returns the next smaller positive integer?
body: <p>I am trying to write a function that takes a positive integer and returns the next smaller positive integer containing the same digits, and -1 when there is no smaller number that contains the same digits. </p>
  
  <pre><code>For example:
  
  nextSmaller(21) == 12
  nextSmaller(531) == 513
  nextSmaller(2071) == 2017
  </code></pre>
  
  <p>I wrote a code that solves this, but I don't really know how to optimize it further. Could you please help me? It runs fairly fast on repl.it, but when I submit it, it says it takes more than 1200ms and doesn't allow me to submit it even though all the tests pass.</p>
  
  <pre><code>function nextSmaller(n) {
  var nArray= n.toString().split("")
  var minimumNum = 1 + Array(nArray.length).join('0')
  for(var i=n-1; i &gt;= minimumNum; i--) {
    var newNumArray = i.toString().split('');
    var counter = 0;
    for (var j=0; j&lt;newNumArray.length; j++) {
      if (nArray.indexOf(newNumArray[j]) &gt; -1) {
          counter++
          nArray.splice(nArray.indexOf(newNumArray[j]), 1)
          if (counter === n.toString().split("").length) {
          return i;
          }
       } 
    }
         nArray = n.toString().split("");
         if (i === Number(minimumNum)) return -1;
    }
  }
  </code></pre>