0

I've faced a problem in js when looping over arrayitems within a forEach function. I simply have an Array of IDs, where some IDs have less than 10 Characters, which I want to fill with "0" at the beginning. Example: myArray = ["1234567890", "0123456789", "12345678"] In that case I want to fill up the last item with "0" --> "0012345678". Of course it's also possible in various other ways, but I simply don't get why it doesn't work.

Here's my code:

myArray.forEach(Id =>{
    while(Id.length < 10){
        Id= "0" + Id;
    }
})
a.ak
  • 659
  • 2
  • 12
  • 26
itsmeMarc
  • 13
  • 1

2 Answers2

3

When you do Id= "0" + Id;, you're just updating the parameter value. That parameter value isn't saved anywhere when you're done.

If you want to update the values in the array, either assign back to the existing array or (more commonly) create a new array via map:

myArray = myArray.map(Id => {
    while (Id.length < 10) {
        Id = "0" + Id;
    }
    return Id;
});

Or these days, you could use padStart instead of the while loop:

myArray = myArray.map(Id => Id.padStart(10, "0"));

Here's an example of assigning back to the original array, in case you wanted to do that:

myArray.forEach((Id, index) => myArray[index] = Id.padStart(10, "0"));

Live Examples:

// Creating a new array (1)
let myArray1 = ["1234567890", "0123456789", "12345678"];
myArray1 = myArray1.map(Id => {
    while (Id.length < 10) {
        Id = "0" + Id;
    }
    return Id;
});
console.log(myArray1);

// Creating a new array (2)
let myArray2 = ["1234567890", "0123456789", "12345678"];
myArray2 = myArray2.map(Id => Id.padStart(10, "0"));
console.log(myArray2);

// Updating the existing array
let myArray3 = ["1234567890", "0123456789", "12345678"];
myArray3.forEach((Id, index) => myArray3[index] = Id.padStart(10, "0"));
console.log(myArray3);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks for the faster answer, works now ! btw. what's the reason i don't need a return value in your second example wit the padStart function ? – itsmeMarc May 21 '21 at 07:23
  • @itsmeMarc - That's a concise-form arrow function (there's no `{` after the `=>`). The body consists entirely of a single expression, and that expression's result is the return value of the function. More [here](http://stackoverflow.com/questions/24900875/whats-the-meaning-of-an-arrow-formed-from-equals-greater-than-in-javas) and [here](https://stackoverflow.com/questions/45754957/why-doesnt-my-arrow-function-return-a-value) (and in Chapter 3 of my recent book -- links in my profile if you're interested). – T.J. Crowder May 21 '21 at 07:40
0

If you want to use forEach you must fetch the array also and change its content.

myArray.forEach((Id, index, arr) =>
{
    while(Id.length < 10){
        Id = "0" + Id;
    }
    arr[index] = Id;
});
Thallius
  • 2,482
  • 2
  • 18
  • 36