Unveiling the Secret: Removing Duplicate Elements from an Array

I'm attempting to create a JavaScript function that can remove duplicates from an array without using the Set, filter, or reduce functions. I've tried using nested loops to compare elements and splice duplicates out of the array, but I seem to be stuck on how to properly remove them. Here is my current code:

function clearDuplicatesInArray(arr) {
 for (let i = 0; i < arr.length; i++) {
   for (let j = 0; j < arr.length; j++) {
      if (arr[i] === arr[j]) {
       arr.splice(i, 1);
      }
    }
  }
 return arr;
}

clearDuplicatesInArray([1, 1, 2, 3]);

Answer №1

To avoid unnecessary slicing on unvisited indices, consider iterating from the end and using a secondary loop up to the outer index where items are already visited.

When splicing, provide the index plus one as a parameter to remove one element at that specific index.

function eliminateDuplicates(array, item) {
    var i = array.length,
        j;
    
    while (--i) {
        for (j = 0; j < i; j++) {
            if (array[i] === array[j]) {
                array.splice(i, 1);
                break;
            }
        }
    }
    return array;
}

console.log(eliminateDuplicates([1, 1, 2, 3]));

Answer №2

Let me provide a solution for your code, but keep in mind that there are multiple ways to achieve the desired result.

function removeDuplicatesFromArray(arr) {
 for(i = 0; i < arr.length; i++) {
   for(j = i+1; j < arr.length; j++) {
      if(arr[i] === arr[j]) {
       arr.splice(i, 1);
       i--;
       break;
      }
    }
  }
 return arr;
}

console.log(removeDuplicatesFromArray([1,1,2,3]));

Answer №3

function removeDuplicates(array) {
   var newArr = array.slice(); //create a copy of the original array
   for(let i = 0, length = newArr.length; i < length; i++) {
      if(newArr.indexOf(newArr[i]) != newArr.lastIndexOf(newArr[i])) {
         newArr.splice(newArr.indexOf(newArr[i]), 1);
         i--;
      }
   }
   return newArr;
}

This custom function identifies and removes duplicate values from an array.

It makes use of both the slice and splice methods in its logic.

input:
removeDuplicates([1,1,2,3,4,4,7]);

output:
Array(5) [ 1, 2, 3, 4, 7 ]

Answer №4

To eliminate duplicates efficiently, you can employ the value itself as a key using O(n) complexity.

function removeDuplicates(arr, item){
    var uniqueValues = {};
    for(value of arr){
        uniqueValues[value] = value;
    }
    return Object.values(uniqueValues);
}
console.log(removeDuplicates([1,1,1,2,1,4,2,3]));

Answer №5

Here is an alternative method to achieve the same result using a single loop:

1) Organize the elements in the array.

2) Execute a backward loop (to prevent issues with splicing).

arr = arr.sort();

let i = arr.length;
while (--i) {
    if (arr[i] == arr[i-1]) {
    arr.splice(i, 1);
  }
}

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

step-by-step guide for resolving issues with downloading files in node.js

I've been attempting to download files from my server using node.js with the res.download function from Express, but I keep getting an undefined error. The folder path is D:\program\web\java_script\Node\my_project\ketabk& ...

Cordova Application experiencing freeze on loading Splash Screen

My issue lies in the behavior of the app built with Backbone.js and Cordova. Everything works smoothly when there is an active network connection, but things change when the device goes offline. During each launch under offline conditions, the app exhibits ...

Exploring Quadrics with Marching Cubes in Three.js

I have been attempting to create an applet that displays various types of space quadrics using the Marching Cubes library from three.js to render implicit surfaces. However, the shapes that are being generated do not appear as expected, leading me to belie ...

I'm seeking clarification on the composition of Objects in Node.js

After running a console.log on a parameter from the callback function in the Node.js formidable package, here is the output of files: { fileUpload: [ PersistentFile { _events: [Object: null prototype], _eventsCount: 1, _maxListene ...

When using the Android platform, the webpage may not be loading correctly and certain links may be unresponsive in the webview

While viewing my webpage on Google Chrome in my Android phone, the website loads perfectly and functions as expected. However, when I try to load the same webpage in Webview, the site does not load correctly, especially the jQuery content. Additionally, no ...

Can Express POST / GET handlers accommodate the use of jQuery?

I created a simple Express server to retrieve data from an HTML form and make queries to OpenWeatherMap using that data: const { OpenWeatherAPI } = require("openweather-api-node"); const express = require("express"); const bodyParser = ...

Retrieving only the time value from an Angular controller variable when using an HTML input with type="time"

I have a HTML input field: <input type="time" id="exampleInput" name="input" ng-model="ctrl.time" placeholder="HH:mm:ss" min="00:00:00" max="24:00:00" required /> When I enter a time into the input, it is stored in 'ctrl.time&a ...

jQuery Form Validation - Unusual Redirect Situation

Hey there, I'm currently working on implementing form validation using jQuery. I've encountered a strange issue where clicking submit seems to redirect to the same page instead of validating the form. The action of the form is left blank and I&a ...

Tips for setting a jQuery variable equal to the value of a JSON object

When I try to assign courseid and batchid as defaults using defaultValue => defaultValue: courseid and defaultValue: batchid, the values are not being saved correctly in my database. $(document).ready(function() { var courseid = null; var bat ...

What is the reason why createServer() is often not recognized as a function?

After installing express globally and npm on my express app, I am encountering issues with both intellisence and the app itself (I am using visual studio code on mac OS Yosemite). Below is a snippet of the code: /// <reference path="typings/node/node. ...

Can a snapshot be taken of an auto-generated ID document in FireStore?

Currently, I am working on developing both a mobile app and web app for my Final Year Project. As someone relatively new to Firestore, I am using a single instance of it to store data. When a customer registers through the mobile app, their information ge ...

I am interested in swapping out the text links in a menu for images

Looking to swap out text links in a menu for images, but stuck with template constraints generated by rapidweaver. The HTML template can't be modified, except for the link text itself. For example: <a href="http://truehealth.gr/eng/" rel="">!UK ...

What is the best way to initiate a fresh AJAX request whenever the submit button is pressed?

Every time the submit button is clicked on my form, a modal appears and gets filled with JSON data from the application /addresschecker. If I receive an error message with a code return number of 2003, it indicates an issue with the addresses provided. Oth ...

vue-router: error encountered while attempting to load asynchronous component for rendering

I'm new to vue-router and having trouble getting it to work. When I try to start my app, these errors pop up: [vue-router] Failed to resolve async component render: TypeError: _vm is undefined 49:16:39 [vue-router] uncaught error during route navigat ...

Redux state not reflecting changes until second click

My redux store has a simple boolean setup to track whether a sidebar is expanded or not. However, I'm encountering an issue where, even though the default value is false, clicking the toggle button outputs false first. Ideally, if it's initially ...

Successively linking promises together within a for-each iteration

How can I ensure that a foreach loop is synchronous in AngularJS var articles = arg; articles.forEach(function(data){ var promises = [fetchImg(data), fetchUser(data)]; $q.all(promises).then(function (res) { finalData.push(res[1]); ...

A guide to resolving cross-origin resource sharing issues using a reverse proxy

After creating a JavaScript web application for processing documents, I am now looking to integrate with web services like NLTK-server, TIKA-server, and SOLR for further analysis. While I can successfully access the REST endpoints of these services using c ...

Vue JS: Breathing Life into Your Elements

Incorporating Vue-Router and Vuex, I have successfully implemented a Users Profile Component that fetches user information by extracting the username parameter from a router-link. For example, <router-link :to="{name: 'user', params: { usernam ...

What steps should I take in modifying my existing code to use jQuery to set my div to a minimum height rather than a fixed height?

Could someone assist me in adjusting my div to have a min-height instead of a regular height? Whenever I click on the "Learn more" button, it extends past my div because the function is designed to set a specific height rather than an equal height. $.fn.e ...

Sending a JSON object as a prop from one React.js component to another

I've been attempting to pass a JSON object retrieved by calling a REST API after submitting a form with user input. While I am successful in transferring the data to another component within the same file (this component is responsible for iterating o ...