Why using filter() in Javascript failed?


  • 0
    I

    I don't understand why this implementation fails. First I filter all zeros from the array, then add all missing zeros at the end of the array. By logging the array at the end of the method showing expected result, but submission is Wrong Answer.

    var moveZeroes = function(nums) {
        var c = nums.length;
        nums = nums.filter(n => n !== 0);
        var c1 = nums.length;
        for(var i = 0; i < c - c1; i++) {
            nums.push(0);
        }
        console.log(nums);
    };

  • 0

    filter will make a copy of the array


  • 0
    S

    filter method returns a new array
    then reference of nums has been changed


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.