Link to the problem:
My code is almost correct but I don’t know how to change it to get the wanted output:

var removeElement = function(nums, val) {
let arrLength = nums.length;
for(var i = 0;i < arrLength ;i++){
if(nums[i] === val){
nums.shift();
}
}
var newArrLength = nums.length;
return newArrLength;
};
What should I add/change to get the wanted output?
Thanks in advance for the help!
Regards
Ma3_str0
Shift removes the first element in the array. Use nums.splice(i, 1)
instead to remove the element at index i. After that, reduce the index i
by 1 because you have changed the position of the remaining elements in the array. Setting the length of the array before the loop will give you wrong answer. Instead use for(var i = 0;i < nums.length ;i++)
1 Like
Just using the splice was enough ,it accepted my answer at first but now it gives errors for other inputs. Should I reduce the index via a for loop?
Immediately after nums.splice(i, 1)
add i--
thx once again man, could I dm you if I struggle with some more of these problems?
You can. Though i can’t guarantee that i will give a quick response. To be helped fast you have to post here on the forum.