Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
Javascript Remove Duplicates Ints From Array

I'm working on a Leet code challenge where I'm trying to remove all duplicates from a sorted ascending array of integers.

So for example [1,1,1,2,2,3,4,5,5,5] should return [1,2,3,4,5].

I have solved this one way, but was trying a different way as per the code below, but it seems to always return an empty array [].

Could anyone point me in the direction (of what might be very obvious but I havent seen it) of why this always returns an empty array?

var removeDuplicates = function(nums) {
    
    for(let i = 0; i < nums.length; i++) {
        let counter = 0;
        for(let x = i + 1; x < nums.length; x++) {
            // Remove element if above is true
            if(nums[i] == nums[x]) {
                counter++;
            }
        }
        nums.splice(i + 1, counter);
    }
    return nums;
};

console.log(removeDuplicates( [1,1,1,2,2,3,4,5,5,5] ));

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You will get an empty array, because your algorithm is wrong. Your algorithm will works correctly just when the similar numbers are side by side each other. For example:

[1,1,1,2,2,5,5,5,5,5,3,3]

Otherwise it doesn't work correctly.

There are lots of algorithm to remove duplicated values from an array. Please have a simple search to find them. But you can easily remove duplicate values in an array in these ways:

function removeDuplicates(numbers) {
    return [...new Set(numbers)];
}

Or:

function removeDuplicates(numbers) {
    return numbers.filter((num, index, self) => index === self.indexOf(num));
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!