MeltingDog
MeltingDog

Reputation: 15490

JavaScript: Is it possible to update the value of an array item with forEach?

I want to cycle through an array of numbers and if any of those numbers are single digit add a 0 before it, eg 1 becomes 01.

I could do this with a for loop but was wondering if I could use forEach as it seems neater.

Would anyone know if this can be done?

My code so far:

  numArr.forEach(function(item) {
    if (item < 10) {
      item = '0' + item; // How do I update this value in array?
    }
  });

Upvotes: 1

Views: 153

Answers (5)

Saurabh Yadav
Saurabh Yadav

Reputation: 3386

you can use padStart and map

var cont = [1, 2, 3, 4, 5, 6, 7, 10, 11, 12];
var result = cont.map((o)=>{ return o.toString().padStart('2', 0);});

console.log(result);

Upvotes: 0

Vikas
Vikas

Reputation: 7205

You can use map,

var numArr = [1, 2, 3,10,11];
numArr = numArr.map(function(item) {
   if (item < 10) {
      return item = '0' + item;;
    }
  return item.toString() ;
});
console.log(numArr);

One more oprtion is to use forEach with two parameters(second parameter will be index),

var numArr = [1, 2, 3,10,11];
numArr.forEach(function(item,index) {
   if (item < 10) {
      numArr[index] = '0' + item;
    }
  
});

console.log(numArr);

Upvotes: 1

jo_va
jo_va

Reputation: 13993

If you want to modify your array in place, then Array.forEach() is the way to go and you'll have to use the index for that, which is the second argument of your callback.

However, if you want to generate a new array, I suggest using Array.map() which returns a new item for each iteration:

const numArr = [-1, 0, 1, 2, 3, 10, 11, 12, 100, 3.14];

const prefix = x => {
  const s = `0${x.toString().replace('-', '')}`;
  return s.split('.')[0].length >= 3 ? `${x}` : `${x < 0 ? '-' : ''}${s}`;
}

const result = numArr.map(prefix);

numArr.forEach((x, i) => numArr[i] = prefix(x));

console.log(result);
console.log(numArr);

Upvotes: 1

Mamun
Mamun

Reputation: 68933

You pass index as the second parameter to event handler function and use that index to modify the item in array:

numArr.forEach(function(item, i) {
  if (item < 10) {
    numArr[i] = '0' + item; // How do I update this value in array?
  }
});

You can also use map():

numArr = numArr.map(function(item, i) =>  {
  if (item < 10) {
    item = '0' + item; // How do I update this value in array?
  }
  return item;
});

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386883

You could map the array with Array#map and convert the value to string and pad with a wanted length and value.

var numArr = [1, 2, 3, 10],
    zeroes = numArr.map(v => v.toString().padStart(2, '0'));

console.log(zeroes);

Upvotes: 1

Related Questions