Smallest number formed by shuffling one digit at most in JavaScript


We are required to write a JavaScript function that takes in a positive number n. We can do at most one operation −

Choosing the index of a digit in the number, remove this digit at that index and insert it back to another or at the same place in the number in order to find the smallest number we can get.

Our function should return this smallest number.


Following is the code −

 Live Demo

const num = 354166;
const smallestShuffle = (num) => {
   const arr = String(num).split('');
   const { ind } = arr.reduce((acc, val, index) => {
      let { value, ind } = acc;
      if(value > val){
         value = val;
         ind = index;
      return { value, ind };
   }, { value: Infinity, ind: -1 });
   const [item] = arr.splice(ind, 1);
   return Number(arr.join(''));


Following is the console output −