Posted By

DADU on 08/13/10


Tagged

javascript list numbers array zero leading integers


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

DADU


add leading zeros


 / Published in: JavaScript
 

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.

  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  

You need to login to post a comment.