1

I want to retain the array instead of creating a new one (which map does), hence, I'm doing the following using forEach. But none of my comparisons are going through and the array remains the same.

const array1 = [1, 2, 3];

array1.forEach(element =>  element < 2 ? 0 : element);
//array1.forEach(element =>  element + 2);
console.log(array1);

The result should be array1 = [0, 2, 3];

Is my understanding of how it works incorrect?

Nikhat
  • 41
  • 9
  • 2
    `.forEach()` doesn't modify the array. You're probably looking for `.map()`. Do remember that `.map()` returns a new array. – VLAZ Oct 25 '22 at 08:57
  • 2
    `array1.forEach((element, idx) => { if (element < 2) array1[idx] = 0; });` – Yousaf Oct 25 '22 at 08:59

2 Answers2

2

It's not a good idea to modify the original array which may make some conflicts, it would be better to use map,

But If this is the only case you need, you can use forEach and get the element by its index and reassign it like element < 2 && (arr[index] = 0)

const array1 = [1, 2, 3];

array1.forEach((element, index, arr) =>  element < 2 && (arr[index] = 0));

console.log(array1);
Mina
  • 14,386
  • 3
  • 13
  • 26
  • Thank you. Can you please tell me what kind of conflicts it might cause? – Nikhat Oct 25 '22 at 09:23
  • 1
    @Nikhat, you are welcome, In your simple case it will not make any conflicts, but in other cases, It can make, for example, if you `splice` the array inside the `forEach` because `splice` method can effect the origin array add/remove items. – Mina Oct 25 '22 at 09:26
1

Use map (and reassign the initial array), or use the thisArg argument with forEach (see MDN). Note: in the forEach with thisArg the lambda can not be an arrow function (that would not bind this):

let array1 = [1, 2, 3];
let array2 = [...array1];
let array3 = [...array1];
let array4 = [...array1];
// remap
array1 = array1.map( el => el < 2 ? 0 : el );

// with foreach, use the 'thisArg' parameter
array2.forEach( function(el, i) { this[i] = this[i] < 2 ? -1 : el }, array2 );

// not advisable, but other possibilities
array3 = array3.filter(el => el < 2).map(_ => -2)
  .concat(array3.filter(el => el >= 2));
array4 = array4.reduce( (acc, el) => [...acc, el < 2 ? -3 : el], [] );
console.log(`[${array1}, [${array2}], [${array3}], [${array4}]`);
KooiInc
  • 119,216
  • 31
  • 141
  • 177