JavaScript Program to Remove Duplicate Elements From a Sorted Array
Last Updated :
15 May, 2024
Given a sorted array arr[] of size N, the task is to remove the duplicate elements from the array.
Examples:
Input: arr[] = {2, 2, 2, 2, 2}
Output: arr[] = {2}
Explanation: All the elements are 2, So only keep one instance of 2.
Input: arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}
Output: arr[] = {1, 2, 3, 4, 5}
These are the following approaches:
Using for loop
In this approach, The removeDup function removes duplicate elements from a sorted array. It iterates through the array, comparing each element with its adjacent element. If they are not equal, the current element is added to a new array uniqueArray. Finally, the function returns uniqueArray, which contains unique elements. The provided example removes duplicates from sortedArray and logs the result to the console.
Example: This example shows the implementation of the above-explained approach.
Javascript
function removeDup(sortedArray) {
let uniqueArray = [];
for (let i = 0; i < sortedArray.length; i++) {
if (sortedArray[i] !== sortedArray[i + 1]) {
uniqueArray.push(sortedArray[i]);
}
}
return uniqueArray;
}
const sortedArray = [1, 2, 2, 3, 3,
3, 4, 5, 5];
const uniqueArray = removeDup(sortedArray);
console.log("Array with Duplicates Removed:",
uniqueArray);
OutputArray with Duplicates Removed: [ 1, 2, 3, 4, 5 ]
Using While loop
The removeDup function removes duplicate elements from a sorted array sortedArray. It uses a while loop with an index i to iterate through the array. Each element is compared with its adjacent element. If they’re not equal, the element is added to `unique
Example: This example shows the implementation of the above-explained approach.
Javascript
function removeDup(sortedArray) {
let uniqueArray = [];
let i = 0;
while (i < sortedArray.length) {
if (sortedArray[i] !== sortedArray[i + 1]) {
uniqueArray.push(sortedArray[i]);
}
i++;
}
return uniqueArray;
}
const sortedArray = [1, 2, 2, 3,
3, 3, 4, 5, 5];
const uniqueArray = removeDup(sortedArray);
console.log("Array with Duplicates Removed:",
uniqueArray);
OutputArray with Duplicates Removed: [ 1, 2, 3, 4, 5 ]
Using the Set object
In this approach we are using the Set object in JavaScript to remove duplicate elements from a sorted array. Here we convert the array into a Set. A Set is a collection of unique values, so any duplicate elements in the array will be automatically removed.
Example: In this example we are using above-explained approach.
JavaScript
let sortedArray = [1, 1, 2, 2, 3, 3, 4, 4, 5];
let uniqueArray = [...new Set(sortedArray)];
console.log("Array with duplicates removed: ");
console.log(uniqueArray);
OutputArray with duplicates removed:
[ 1, 2, 3, 4, 5 ]
Share your thoughts in the comments
Please Login to comment...