Home > Enterprise >  Mutating elements in an array in Javascript
Mutating elements in an array in Javascript

Time:11-21

Ok so I want to subtract 9 to numbers(elements in an array) over 9:

finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8]

Thats what I tried

finalCredDigits.forEach(arr =>{
  if(arr > 9){
    finalCredDigits.push(arr - 9);
  } 
});
Output = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8, 1, 9, 7, 7, 5, 5, 1]

I know its cuz the result is being pushed in the array but i want to mutate it and replace the answer with numbers over 9

CodePudding user response:

If you want a similar but new array, you should use Array.map():

const finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8];
const newFinalCredDigits = finalCredDigits.map(v => {
  if (v > 9) {
    return v - 9;
  } else {
    return v;
  }
});

console.log(newFinalCredDigits.join());
console.log("Is new array?", newFinalCredDigits !== finalCredDigits);

If you want to mutate the array itself with Array.forEach(), you should use the callback's additional parameters:

const finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8];
finalCredDigits.forEach((v, i, array) => {
  if (v > 9) {
    array[i] = v - 9;
  }
});

console.log(finalCredDigits.join());

But functional programming usually implies preferring immutable over mutable states, so if your array is shared and we'd mutate it with Array.forEach(), it would be considered a code smell. Therefore I'd use a regular for-loop instead:

const finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8];
{
  const l = finalCredDigits.length;
  for (let i = 0; i < l;   i) {
    if (finalCredDigits[i] > 9) finalCredDigits[i] -= 9;
  }
}

console.log(finalCredDigits.join());

CodePudding user response:

Try this

let finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8]

finalCredDigits = finalCredDigits.map(number => {
 if (number > 9) {
   return number - 9
 }

  return number
})

console.log(finalCredDigits)

CodePudding user response:

You need to assign to the array index to replace the element, not push a new element.

forEach() passes a second argument to the callback function, containing the current index. You can use this for the assignment.

const finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8];

finalCredDigits.forEach((el, i) =>{
  if(el > 9){
    finalCredDigits[i] = el - 9;
  } 
});

console.log(finalCredDigits);

  • Related