To replace null with 0 in an array, go through the following steps:
forEach()
method.element
, and index
, to the forEach()
method.null
.null
, set the value to zero at that index position.let arr = [24, 12, null, 21, 8, null, 33, 5]; arr.forEach((element, index) => { if(element === null){ arr[index] = 0; } }); console.log(arr); //[24, 12, 0, 21, 8, 0, 33, 5]
The forEach() method is used to iterate through an array. It accepts two parameters:
this
variable inside the callback function, then this
points to the value passed to the thisArg
parameter.Another way to replace null
with 0 is to use the map()
method.
The map() method updates each array element without modifying the original array.
Inside the callback function of the map()
method, compare each element with null
. If an element is null
, return 0; otherwise, return the element.
let arr = [24, 12, null, 21, 8, null, 33, 5]; let result; result = arr.map(element => { if(element === null){ return 0; }else{ return element; } }); console.log(result); //[24, 12, 0, 21, 8, 0, 33, 5]