Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all occurrences of a number from an array in place [duplicate]

Tags:

javascript

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;
};

1 Answers

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

like image 106
Jaromanda X Avatar answered Sep 02 '25 14:09

Jaromanda X



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!