Open In App

JavaScript Program to Remove Duplicate Elements From a Sorted Array

Last Updated : 16 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Table of Content

Approach 1: 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);


Output

Array with Duplicates Removed: [ 1, 2, 3, 4, 5 ]

Approach 2: 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);


Output

Array with Duplicates Removed: [ 1, 2, 3, 4, 5 ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads