It is my goal to populate the array with numbers while avoiding any duplicate entries

I am currently facing an issue with my code as it is returning a length of 0 instead of the expected result of 5 after excluding duplicates from the array. I have a feeling that there might be something missing in my code, but I just can't seem to figure out what it is. Could someone please take a quick look and let me know what needs to be corrected? I would really appreciate it if the solution could use my existing code rather than starting from scratch. Thank you!

Question: Given a sorted array nums, remove the duplicates in-place such that each element appears only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

const numbers = [0,0,1,1,1,2,2,3,3,4]

const removeDuplicates = (nums) => {
    nums.sort()
    const newArr = []

    //Alternatively, count the number of unique elements
    for(let i = 0; i < nums.length; i++){
        for(let j = 0; j < nums.length; j++){
            if(!nums[i] === nums[j]){
                 newArr.push(nums[i]);
            }
        }
    }
    console.log(newArr)
    return newArr.length
};

Answer №1

The issue with your code lies within this particular line:

            if(!nums[i] === nums[j]){

You likely meant to write it as:

            if(nums[i] !== nums[j]){

Furthermore, there seems to be a flaw in the logic of using nested for loops. It appears that what you actually intended was:

const numbers = [0,0,1,1,1,2,2,3,3,4]

const removeDuplicates = (nums) => {
    nums.sort((a, b) => a - b);
    const newArr = [];

    let prev = -Infinity;
    for (let i=0; i<nums.length; i++) {
        if (nums[i] === prev)
            continue;
        newArr.push(nums[i]);
        prev = nums[i];
    }

    console.log(newArr);
    return newArr.length;
};

removeDuplicates(numbers);

Answer №2

If you want to accomplish this task without creating a new array, you can achieve it by using the array.splice() method as shown below:

let index = numbers.length - 1
do {
  let x = numbers.indexOf(numbers[index])
  if ( x !== index ) {
    numbers.splice(x,1)
  }
  index -= 1
} while ( index > 0 )

Answer №3

To accomplish this task, you can utilize the `reducer` method in JavaScript.

    const elements = [4,4,6,6,8,10,10,12,12,14]
    const reducerFunction = (accumulator, currentValue) => {
      if(accumulator.indexOf(currentValue) === -1){
        return [...accumulator, currentValue]
      }
      return accumulator
    }
    
    const eliminateDuplicates = array => array.reduce(reducerFunction, []);
    
    eliminateDuplicates(elements) // -> result [4, 6, 8, 10, 12, 14 ]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What distinguishes defining a function through a prototype versus as a class property?

Check out this code snippet: Apple defines its function using a prototype. Banana defines its function using a class property. var Apple = function(){} Apple.prototype.say = function(){ console.debug('HelloWorld'); } var Banana = functio ...

What is the best way to slice the string into segments and organize them within an array?

On my website, there is a text box where users can input a series of numbers in the following format: (118,38,137,15,156,14,157,36,152,49,142,57) I want to know how I can store these numbers in an array as shown below: [118 38 137 15 156 1 ...

Can the parent document interact with Shadow DOM elements?

When it comes to user-created shadow DOM elements, this question focuses more on accessibility using the date input type: For instance, let's say there is a date input on a webpage. After some editing, the shadow DOM markup for this element (in Chrom ...

Press anywhere on the screen to conceal the AngularJS element

Attempting to create a toggle effect using 2 ng-click functions. One is bound to a button, the other to the body tag. The goal is for my content to show when the button is clicked and hide when anywhere on the body is clicked. However, it seems that Angul ...

React state is not refreshing as expected

I am having trouble updating the state with new employee data. The push function is not inserting the new employee data into the state. In the addPar function, I set up a console log and it shows that the data is there, but it fails to push it to the sta ...

Node.js utilized for conducting anti-virus scans on server-bound files prior to uploading

Is there a way for me to scan files that are submitted as request payloads to check if they contain potential viruses? For example, if someone tries to upload a txt file with the EICAR virus signature, I want to be able to scan it and reject it if it is in ...

Utilizing Async/Await with Node.js and Mongoose

Learning Promises and async/await programming is a new challenge for me, especially in the context of creating an API using Nodejs, Express, Mongoose, and MongoDB. While most tutorials focus on handling asynchronicity within a single file containing routin ...

"The Material UI date picker is encountering an issue with the error prop, which is being evaluated

I have developed a date picker that utilizes the Jalali calendar. While attempting to pass error checking using the error prop in the following code: <LocalizationProvider dateAdapter={AdapterJalali}> <MobileDatePicker label={lab ...

Tips for creating a stylish navbar with a faded effect on the right side and integrating a fresh button into its design

I'm looking to enhance my Navbar by implementing a feature where, if the width of the Navbar exceeds that of its parent div, it will fade on the right side and a new button will be added - similar to what can be seen on Youtube. 1- When the Navbar&ap ...

How is it that a callback function can successfully execute with fewer arguments provided?

Code I'm really intrigued by how this code functions. In the verifyUser function, it passes a callback function as the fourth argument to the verifyToken function. However, upon examining the verifyToken function itself, I noticed that it only has th ...

Is there a way to enlarge an iFrame to fill the entire screen with just a button click, without using JavaScript

I am currently attempting to achieve full screen mode for an iFrame upon clicking a button, similar to the functionality on this site. On that website, there is a bar that expands to full screen along with the embedded game, which is what I am aiming for. ...

What are the best practices for presenting Motion JPEG binary data streams using Angular, Ionic, and JavaScript?

I am developing an application for a device that will receive a POST request and send back a binary data stream in the format of multipart/x-mixed-replace. My goal is to display this stream on a specific section of my app's homepage. After conducting ...

Rotate the circular border in a clockwise direction when clicked

I have successfully designed a heart icon using SVG that can be filled with color upon clicking. Now, I am looking to add an outer circle animation that rotates clockwise around the heart as it is being created. Currently, the circle only spins in the code ...

Guide to verifying current data using the jQuery validation library combined with CodeIgniter 4 in the presence of automatic CSRF protection

I am currently working on validating a form using the jQuery validation plugin and CodeIgniter 4. I have enabled CSRF protection that auto generates for each request. Initially, I can successfully validate the form on the first request. However, on subsequ ...

Ensuring AngularJS ui-router/app waits for $http data to avoid Flash of Unstyled Content (FOUC)

My question or situation pertains to the states defined in my AngularJS application. Here is an example of how I have them structured: $stateProvider .state('myApp', { abstract: true, template: '& ...

Looking for a way to efficiently retrieve results by matching multiple string keywords as you go through each line of a file (fs)?

Essentially, I have multiple search strings provided by the client that need to be matched with each line in a file. If a line matches all of the inputted strings, I should add that line to the results array. However, when I run the code below, it only ret ...

Is the window frozen while Ajax processes the request?

When I make an ajax request that may take a significant amount of time to process on the server-side, I want to display a loading image during the request. However, the loading image is not showing up while the ajax request is processing. var ref = create ...

Provide the identification number of a specific row within the modal

I am trying to pass the id of a specific row into a modal popup Link code: <a href="#myModal" class="btn btn-default btn-small" id="custId" data-toggle="modal" data-id="<? echo $row['id']; ?>">Resume</a> Modal code: <div ...

"Enhance your website with dynamic PHP Ajax live search and infinite scrolling

When scrolling to the bottom of the .dropdown-menu, I would like to load an additional 7 rows from the database. However, I haven't been successful in implementing this feature using the script provided. I am currently utilizing Bootstrap CSS and JS f ...

What is the best way to form an array containing associative subarrays from a one-dimensional array?

Below is an array that I am working with. Array( [1041] => 30 [1046] => 10 [1047] => 10 ) I would like to restructure it as follows. Array([0] => Array ( [material_name] => 1041 [material_qty] => 30 ) [1] => Array ( [ma ...