It is not a duplicate as I don't seek the answer to a specific problem, I want to understand why my answer to a problem fails.
I'm trying to solve a problem on LeetCode and the functions I create yield correct results on the Chrome DevTools but when I submit them on the website they fail.
I want to understand why they fail and/or aren't accepted.
Example 1:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
Note that the order of those five elements can be arbitrary.
It doesn't matter what values are set beyond the returned length.
My provided answers:
var removeElement = function(nums, val) {
return nums.filter(e => e !== val).length;
};
and
var removeElement = function(nums, val) {
for (i = 0; i < nums.length; i += 1) {
if (nums[i] === val) {
nums.splice(i, 1)
}
}
return nums;
};
Working answer based off the solutions:
var removeElement = function(nums, val) {
for (i = nums.length; i >= 0; i-= 1) {
if (nums[i] === val) {
nums.splice(i, 1);
}
}
return nums.length;
};