Efficient Techniques for Removing Duplicate Elements from JavaScript Arrays
Method 1: Using a New Array for Comparison
This approach iterates through the original array and checks each element against a new array. If the element is not found, it is added.
const originalArray = ['x', 5, 5, 5, 7, 9, 9, 'y', 'z', 'x'];
const uniqueArray = [];
const length = originalArray.length;
for (let i = 0; i < length; i++) {
let isDuplicate = false;
for (const item of uniqueArray) {
if (item === originalArray[i]) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
uniqueArray.push(originalArray[i]);
}
}
console.log('Result from Method 1:', uniqueArray);
Method 2: In-Place Deletion with Nested Loops
This method modifies the original array by comparing elements and removing duplciates using splice.
let dataSet = [10, 20, 30, 'p', 'q', 30, 20, 'r', 'p'];
let currentLength = dataSet.length;
while (currentLength-- > 0) {
for (let j = 0; j < currentLength; j++) {
if (dataSet[j] === dataSet[currentLength]) {
dataSet.splice(j, 1);
break;
}
}
}
console.log('Result from Method 2:', dataSet);
Method 3: Utilziing indexOf for Position Comparison
Elements are removed in-place if their first occurrence index does not match the current iteration index.
const numberList = [15, 42, 15, 15, 15, 8, 42, 12, 18, 21, 21, 17, 12];
function eliminateDuplicates(arr) {
for (let idx = 0; idx < arr.length; idx++) {
if (arr.indexOf(arr[idx]) !== idx) {
arr.splice(idx, 1);
idx--;
}
}
return arr;
}
const processedList = eliminateDuplicates(numberList);
console.log('Result from Method 3:', processedList);
Method 4: Building a New Array with indexOf
A new array is constructed by checking if elements exist within it using indexOf.
const mixedValues = ['g', 'h', 100, 200, 300, 300, 300, 'k', 'g'];
const filteredValues = [];
for (let k = 0; k < mixedValues.length; k++) {
if (filteredValues.indexOf(mixedValues[k]) === -1) {
filteredValues.push(mixedValues[k]);
}
}
console.log('Result from Method 4:', filteredValues);
Method 5: Leveraging the filter Method
A concise solution using filter that retains only the first occurrence of each element.
const sampleArray = [22, 33, 44, 22, 33, 55, 66];
const deduplicatedArray = sampleArray.filter((value, position, self) => {
return self.indexOf(value) === position;
});
console.log('Result from Method 5:', deduplicatedArray);