Reputation: 9
I am trying to find the dupicates in an array and removing them at the duplicated index using the splice method, the code is removing the duplicates but it still leaves one duplicated item.
var removeDuplicates = function(nums) {
let length = nums.length;
for(let i=0;i<length;i++){
for(let j=i+1;j<length;j++){
if(nums[i]==nums[j]){
console.log(nums);
nums.splice(j,1)
}
}
}
return nums;
};
console.log(removeDuplicates([1,2,2,2,2,2,2]))
Upvotes: 0
Views: 528
Reputation: 156
There are different ways to remove array duplicates.
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
let unique = [...new Set(names)];
console.log(unique); // 'John', 'Paul', 'George', 'Ringo'
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
let x = (names) => names.filter((v,i) => names.indexOf(v) === i)
x(names); // 'John', 'Paul', 'George', 'Ringo'
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
function removeDups(names) {
let unique = {};
names.forEach(function(i) {
if(!unique[i]) {
unique[i] = true;
}
});
return Object.keys(unique);
}
removeDups(names); // // 'John', 'Paul', 'George', 'Ringo'
https://wsvincent.com/javascript-remove-duplicates-array/
https://medium.com/dailyjs/how-to-remove-array-duplicates-in-es6-5daa8789641c
Upvotes: 0
Reputation: 8168
The problem is you're looping in forward direction and simultaneously removing elements, which messes up the indices.
So, you should loop in backwards direction in this case.
var removeDuplicates = function (nums) {
let length = nums.length;
for (let i = length - 1; i >= 0; i--) {
console.log(`All redundant instances of ${nums[i]} will be removed`);
for (let j = i - 1; j >= 0; j--) {
if (nums[i] == nums[j]) {
nums.splice(j, 1);
}
}
console.log(JSON.stringify(nums));
}
return nums;
};
const result = removeDuplicates([1, 1, 2, 3, 3, 2]);
console.log("Final Result", JSON.stringify(result));
Set
.const
arr = [1, 1, 2, 3, 3, 2],
result = [...new Set(arr)]
console.log(JSON.stringify(result))
Upvotes: 1