# Solving Remove Duplicates from Sorted Array in JavaScript!

--

Today, we’re going to be solving Leetcode’s Problem #26, Remove Duplicates from Sorted Array.

**The Problem Statement:**

This is asking for a lot!

Let’s break down what it’s asking for:

- We are given an array called
, which is randomly sorted.*nums* - We need to remove the duplicate numbers without creating another array (that’s what the in-place part is asking for).
- We then need to return the number of unique items
in the array*(k)*

**Here are the examples they provide:**

To begin doing this, we’re going to create pointers that reference whatever element we’re on in the array and compare them to each other.

The first pointer will begin with the first element in the ** nums** array.

function removeDuplicates(nums){ let pointer1 = 0;}

Our second pointer will need to increment throughout the ** nums **array, so we should put it in our for loop so that we can compare the elements.

Pointer2 needs to start at 1 so that it can be compared to the first pointer (0) which is the first element.

*If this is confusing, think of the index numbers.*

*Indices do not start at 1, they start at 0.*

function removeDuplicates(nums){ let pointer1 = 0;

for (let pointer2 = 1; pointer2 < nums.length; pointer2++){ }}

Now, we will compare the two numbers to each other.

If the number that pointer1 is at doesn’t equal the number pointer2 is at, we’ll want pointer1 to move to the next number.

Then, we want to replace the number pointer1 is at with the number pointer2 is at.

function removeDuplicates(nums){let pointer1 = 0;

for (let pointer2 = 1; pointer2 < nums.length; pointer2++){

if(nums[pointer1] !== nums[pointer2]){

pointer1++;

nums[pointer1] = nums[pointer2]; } }}

Now, the loop will continue until they reach the end of the array.

The last thing we have to do is look at the index of whatever pointer1 has settled on.

But, we need to add a +1 to represent how many unique items there are in the array since pointer1 stops right before the end of the array (because pointer2 is there!)

function removeDuplicates(nums){let pointer1 = 0;

for (let pointer2 = 1; pointer2 < nums.length; pointer2++){ if(nums[pointer1] !== nums[pointer2]){

pointer1++;

nums[pointer1] = nums[pointer2]; } }

return pointer1 + 1;}

✨✨✨And that’s it!

Tish⚡️🎧🌙