add leading zeros


/ Published in: JavaScript
Save to your folder(s)

This JavaScript code snippet checks each integer in an array. If necessary, one or more leading zeros are added to an integer. Note that each integer becomes a string.


Copy this code and paste it in your HTML
  1. /* EXAMPLE
  2.  
  3. document.write(addLeadingZeros([1,2,3,4,5,6,7,8,9,10]));
  4.  
  5. */
  6.  
  7. function addLeadingZeros(array) {
  8.  
  9. var highestInt = Math.max.apply(Math,array);
  10.  
  11. for(var i=0; i<array.length; i++) {
  12.  
  13. var nLeadingZeros = highestInt.toString().length - array[i].toString().length;
  14.  
  15. for(var j=0; j<nLeadingZeros; j++) array[i] = '0' + array[i];
  16. }
  17.  
  18. return array;
  19. }

Report this snippet


Comments


You need to login to view comments.