I am making an attempt at writing a function in JavaScript that accepts an array that has duplicates in it and returns the same array removing duplicates. I know how to this using a Set, filter and reduce but I wanted to try to do it without using those functions. The problem is that I don't know how to splice the duplicate item once I have found them, so how can I just remove the item from the array if it is found as a duplicate, here is my code:
function clearDuplicatesInArray(arr, item) {
for(i = 0; i < arr.length; i++) {
for(j = 0; j < arr.length; j++) {
if(arr[i] === arr[j]) {
arr.splice(arr[i], arr[j])
}
}
}
return arr;
}
clearDuplicatesInArray([1,1,2,3]);
You could iterate form the end, to prevent slicing for indices whixh are not visited yet and use a second loop until the outer index, because over this index, you have already visited the items.
For splicing, take the index and one as parameter, which removes one element at the given index.
function clearDuplicatesInArray(array, item) {
var i = array.length,
j;
while (--i) {
for (j = 0; j < i; j++) {
if (array[i] === array[j]) {
array.splice(i, 1);
break;
}
}
}
return array;
}
console.log(clearDuplicatesInArray([1, 1, 2, 3]));
I am just going to fix your code, although you can get the solution in many different ways.
function clearDuplicatesInArray(arr, item) {
for(i = 0; i < arr.length; i++) {
for(j = i+1; j < arr.length; j++) {
if(arr[i] === arr[j]) {
arr.splice(i, 1);
i--;
break;
}
}
}
return arr;
}
console.log(clearDuplicatesInArray([1,1,2,3]));
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