-2

How to replace a negative number in an array with the value of 0 in JavaScript e.g.

[1,5,10,-2] will become [1,5,10,0]

I tried

function noNeg(arr) {
  let num 
  return num = arr < 0 ? 0 : arr
}

but it only returns the negative into positive not zero.

Andy
  • 61,948
  • 13
  • 68
  • 95
Ayrene
  • 49
  • 1
  • 2
    Hint: `Math.max(num, 0)`. Just apply that to every number in the array. `Array.map` would come in handy. – deceze Dec 08 '22 at 06:01

1 Answers1

1

Simply map over the array and apply a ternary to return 0 if less than 0 ... or the value if greater than 0.

const arr = [1,5,10,-2];

const newArr = arr.map(num => num < 0  ? 0 : num);

console.log(newArr); // gives [1,5,10,0]
gavgrif
  • 15,194
  • 2
  • 25
  • 27