What's up guys, I was just messing arround LeetCode, and different ways to solving this problem (I know the Set way and the for of with array.includes + push, and the filter, but all of them create a new array), and with this method I'm getting this output, can someone explain me why?
P.S. You can't create a new array, just modify the first one.
let nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4];
var removeDuplicates = (nums) => {
for (let i = 0; i < nums.length; i++) {
if (nums[i] === nums[i + 1]) {
nums.splice(i, i + 1);
}
}
};
removeDuplicates(nums);
console.log(nums);
// [0, 1, 3, 4]
As you say, the job of the splice method is to modify the contents of the array. The two args you're passing it are the start position and the delete count. You also need the replacement value, and to keep replacing until that condition is not longer true, so the while loop is also an option:
let nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4];
var removeDuplicates = (nums) => {
for (let i = 0; i < nums.length; i++) {
while (nums[i] === nums[i + 1]) {
nums.splice(i, 2, nums[i]);
}
}
};
removeDuplicates(nums);
console.log(nums);
Output:
[ 0, 1, 2, 3, 4 ]
The first problem is here: nums.splice(i, i + 1);
Array splice method takes 2 arguments, the first one is the index of element, and the second one is a number of elements to replace/remove (it seems you confused the second argument with the end index). Source: Array.prototype.splice()
Another problem is changing the original array, while iterating over it (be very careful with such in-place manipulations, they very often result in some kind of errors). Look at what is happening in your loop:
The solution is to decrement the i after removing the element:
let nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4];
var removeDuplicates = (nums) => {
for (let i = 0; i < nums.length; i++) {
if (nums[i] === nums[i + 1]) {
nums.splice(i, 1);
i--;
}
}
};
removeDuplicates(nums);
console.log(nums);
// [0, 1, 2, 3, 4]