I'm trying to replace any negative integers with 0 in an array. However, I cannot quite figure out what to do from here. I know that my replace method is not correct, but this is what I've tried so far.
function substitute_negatives(array, currentIndex) {
if (currentIndex < array.length) {
if (array[currentIndex] < 0) {
array[currentIndex] = 0;
}
return substitute_negatives(array, currentIndex 1);
}
};
console.log(substitute_negatives([2, -1, 3, -1, 2], 0));
I'm not sure what I'm doing wrong in this problem. Is this possible to also do with a linked list recursively?
CodePudding user response:
When the recursion finishes, you actually need to return the array, so you have to call return array
instead of an empty return
statement.
Also, if currentIndex
is greater than array.length
, then it is too late because arrays are zero-indexed, thus the undefined
. Try using greater-than or equals to.
Try this instead:
function substitute_negatives(array, currentIndex = 0) {
if (currentIndex >= array.length) return array;
if (array[currentIndex] < 0) array[currentIndex] = 0;
return substitute_negatives(array, currentIndex 1);
}
console.log(substitute_negatives([2, -1, 3, -1, 2]));
Note that in the real world, use .map()
instead:
const substitute_negatives = (arr) => arr.map(x => x < 0 ? 0 : x);
console.log(substitute_negatives([2, -1, 3, -1, 2]));