Home > Software engineering >  Removing the space in the loop javascript
Removing the space in the loop javascript

Time:02-05

It is a counter function for descending number. I throw any number and it start to countdown to zero and I add space between them but the Problem is the last space! How can I remove it??

function countDown(number) {
  var s = "";
  for (let i = number; i >= 0; i--) {
    s  = i   " ";
  }
  console.log("{"   s   "}"); // I add the brackets to show the last space  
}
    
countDown(10)


// result is : {10 9 8 7 6 5 4 3 2 1 0 }

CodePudding user response:

This is a great use case for the Array.join function.

function countDown(number) {
  const list = [];
  for (let i = number; i >= 0; i--) {
    list.push(i);
  }
  console.log("{"   list.join(' ')   "}"); 
}
    
countDown(10)


// result is : {10 9 8 7 6 5 4 3 2 1 0}

CodePudding user response:

This is a common pattern that one has to deal with in loops.

Typically you solve this by having a special case in the beggining or end of a loop. In this example it is easy just to have one in the beggining:

function countDown(number) {
  var s = number;
  for (let i = number - 1; i >= 0; i--) {
    s  = " "   i;
  }
  console.log("{"   s   "}"); // I add the brackets to show the last space  
}
    
countDown(10)


// result is : {10 9 8 7 6 5 4 3 2 1 0}

Just assign s to the number in the beggining and decrease the starting number by 1.

CodePudding user response:

With "low-level" Javascript, without builtins, the trick is to add a delimiter before an item, not after it:

function countDown(number) {
   let s = String(number)
   for (let i = number - 1; i >= 0; i--)
      s  = ' '   i
   return s
}

console.log(JSON.stringify(countDown(10)))

If builtins are allowed, you don't even need a loop to produce this result:

result = [...new Array(11).keys()].reverse().join(' ')
console.log(result)

  • Related