
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Removing duplicates from a sorted array of literals in JavaScript
Suppose we are given a sorted array of literals. We are required to write a function that removes all the duplicates from the array in−place such that each element appears only once and returns the new length of the array.
The condition for doing this is that we cannot allocate extra space for another array, we must do this by modifying the input array in−place with O(1) extra memory.
Example
The code for this will be −
const arr = [1, 3, 3, 6, 7, 7, 9, 11, 13]; const removeDuplicates = (arr = []) => { let i=0; while(i < arr.length − 1){ let j = i + 1; if(arr[i] === arr[j]){ arr.splice(j,1); }else{ i++; } }; }; removeDuplicates(arr); console.log(arr);
Output
And the output in the console will be −
[ 1, 3, 6, 7, 9, 11, 13 ]
- Related Articles
- Removing consecutive duplicates from strings in an array using JavaScript
- Removing adjacent duplicates from a string in JavaScript
- Remove Duplicates from Sorted Array in Python
- Remove Duplicates from Sorted Array II in C++
- Unique sort (removing duplicates and sorting an array) in JavaScript
- Removing duplicates from tuple in Python
- Remove duplicates from a array of objects JavaScript
- Removing Negatives from Array in JavaScript
- Removing comments from array of string in JavaScript
- Removing duplicates and inserting empty strings in JavaScript
- Removing duplicates and keep one instance in JavaScript
- Remove Duplicates from Sorted List in C++
- Removing duplicate objects from array in JavaScript
- Remove Duplicates from Sorted List II in C++
- Flattening a deeply nested array of literals in JavaScript

Advertisements