I am working to solve the below problem,
Given an array and a value, remove all instances of that value in place and return the new length.
I have written the below code for it but it always return an empty array.
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
for (var i=0; i< nums.length; i++)
{
if (nums[i] == val)
nums.slice(i);
}
return nums;
};
Use array SPLICE not slice
var removeElement = function(nums, val) {
for (var i=nums.length - 1; i >=0; i--) {
if (nums[i] == val) {
nums.splice(i,1);
}
}
return nums.length;
};
var n = [1,2,3,2,1,2,3,2,1];
console.log(removeElement(n , 1));
console.log(n);
Also, note the function returns nums.length
- as the requirement you stated is that the function returns the new length of the array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With