Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Removing redundant elements from array altogether - JavaScript
We are required to write a function that takes in an array and returns a new array that have all duplicate values removed from it. The values that appeared more than once in the original array should not even appear for once in the new array.
For example, if the input is:
const arr = [763,55,43,22,32,43,763,43];
The output should be:
const output = [55, 22, 32];
Understanding the Approach
We will be using the following two methods:
-
Array.prototype.indexOf()
It returns the index of first occurrence of searched element if it exists, otherwise -1.
-
Array.prototype.lastIndexOf()
It returns the index of last occurrence of searched element if it exists, otherwise -1.
The key insight is that if an element appears only once in the array, its first and last occurrence indices will be the same. If they differ, the element is duplicated.
Solution
const arr = [763,55,43,22,32,43,763,43];
const deleteDuplicate = (arr) => {
const output = arr.filter((item, index, array) => {
return array.indexOf(item) === array.lastIndexOf(item);
});
return output;
};
console.log(deleteDuplicate(arr));
[ 55, 22, 32 ]
How It Works
The function works by filtering elements where the first occurrence index equals the last occurrence index:
const arr = [763,55,43,22,32,43,763,43];
// Let's trace through each element
arr.forEach((item, index) => {
const firstIndex = arr.indexOf(item);
const lastIndex = arr.lastIndexOf(item);
console.log(`${item}: first=${firstIndex}, last=${lastIndex}, unique=${firstIndex === lastIndex}`);
});
763: first=0, last=6, unique=false 55: first=1, last=1, unique=true 43: first=2, last=7, unique=false 22: first=3, last=3, unique=true 32: first=4, last=4, unique=true 43: first=2, last=7, unique=false 763: first=0, last=6, unique=false 43: first=2, last=7, unique=false
Alternative Solution Using Frequency Count
const arr = [763,55,43,22,32,43,763,43];
const removeAllDuplicates = (arr) => {
const frequency = {};
// Count occurrences
arr.forEach(item => {
frequency[item] = (frequency[item] || 0) + 1;
});
// Filter elements that appear only once
return arr.filter(item => frequency[item] === 1);
};
console.log(removeAllDuplicates(arr));
[ 55, 22, 32 ]
Conclusion
Using `indexOf()` and `lastIndexOf()` provides an elegant solution to remove all duplicates entirely. For larger arrays, the frequency counting approach may offer better performance as it requires only two passes through the array.
