I have the following array in number format. Arr[12,713,6…]
, I am trying to convert them to [0012,0713,0006…]
. I tried padstart(4,"0")
but not working, anybody can help?
Asked
Active
Viewed 105 times
0
-
You do realize, `0012` as number will always be `12`. If you want `0012`, you will have to convert it to string. Try `Arr.map((num) => ("0000" + num.toString()).slice(-4) )` – Rajesh Sep 10 '19 at 11:26
-
Those are some strange Unicode characters that you are using... – Mr. Polywhirl Sep 10 '19 at 11:26
-
padStart does work if you convert your number to a string. `Arr.map(number => number.toString().padStart(4, "0"))` – wiesson Sep 10 '19 at 11:29
-
1@Rajesh The commas that OP used are not standard... `Arr[12,713,6…]` They are using a full-width comma instead of a standard comma... https://www.fileformat.info/info/unicode/char/ff0c/index.htm – Mr. Polywhirl Sep 10 '19 at 11:33
3 Answers
0
var array = [12,713,6];
var newArray = [];
array.forEach(function(element) {
newArray.push(element.toString().padStart(4,0));
});
console.log(newArray);
//Or with array.map (requires ECMAScript 5)
console.log(array.map(number => number.toString().padStart(4, "0")))

Tom Marienfeld
- 716
- 3
- 14
0
You can map your array with numbers, before you use padStart
just make sure that the element is a string.
const arr = [1, 2, 323, 32].map((el) => el.toString().padStart(4, '0'));
console.log(arr);

Nicolae Maties
- 2,476
- 1
- 16
- 26
0
You can pad a number by adding n-number of zeroes before the value and then clipping the string n-places from the beginning.
const padLeft = (v, ch, n) => (ch.repeat(n) + v).substr(-n);
let input = [ 12, 713, 6 ];
let output = input.map(x => padLeft(x, '0', 4));
console.log(output);

Mr. Polywhirl
- 42,981
- 12
- 84
- 132