What is the most efficient way to identify the first duplicate number in an array that contains numbers ranging from 1 to the length of the array, ensuring that the second occurrence of the duplicate

Having some trouble with this code snippet. Tried running it but no luck. Here are the test cases:

  1. Input: 2,1,3,5,3,2
    Expected Output: 3;
  2. Input: 2,4,3,5,1
    Expected Output: -1
  3. Input: 2,4,3,5,1,7

Check out the code below:

function FirstDuplicate(array) {
    var a = [5, 2, 3, 4, 2, 6, 7, 1, 2, 3];
    var firstDuplicate = "";
    for (var i = 0; i < a.length; i++) {
        for (var b = i + 1; b < a.length; b++) {
            if (a[i] === a[b])
                firstDuplicate = a.indexOf(a[i]);
            break;
        }
    }
    return firstDuplicate;
}

Answer №1

To efficiently find the first duplicate in an array, you can utilize a Set. By creating an empty Set and continuously adding elements from the array to it, you can easily detect duplicates by checking if the element already exists in the Set. If a duplicate is found, simply return it.

function FindFirstDuplicate(array) {
    let passed = new Set();
    for(let num of array){
      if(passed.has(num)) return num;
      passed.add(num);
    }
    return -1;
}

console.log(FindFirstDuplicate([2,1,3,5,3,2]))
console.log(FindFirstDuplicate([2,4,3,5,1]))
console.log(FindFirstDuplicate([2,4,3,5,1,7]))

Answer №2

To identify the first duplicate in an array, you can create a function that uses an object to keep track of values that have already been seen.

function findFirstDuplicate(array) {
   var seenValues = Object.create(null),
       index = 0,
       val;
   
   for (index = 0; index < array.length; index++) {
       val = array[index];
       if (seenValues[val]) return val;
       seenValues[val] = true;
   }
   return -1;
}

console.log(findFirstDuplicate([1, 7, 3, 5, 4, 2, 9, 3]));
console.log(findFirstDuplicate([1, 7, 3, 5, 4, 2, 9, 6]));

Answer №3

By iterating over an array, we can push elements into an object. Once an element is encountered for the first time, it is labeled as true. If another true is found, we have identified the first duplicate in the array.

function findFirstDuplicate(arr) {
  let tmp = {};
  return (arr.find(v => (tmp[v] || (tmp[v] = true) && false)) || -1)
}

console.log(findFirstDuplicate([2,1,3,5,3,2]))
console.log(findFirstDuplicate([2,4,3,5,1]))
console.log(findFirstDuplicate([2,4,3,5,1,7]))

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

A new long polling AJAX request is triggered whenever there is a change in the parameter

function AjaxRequest(params, url) { if (params) { this.params = params; this.type = "GET"; this.url = url; // this.contentType = "multipart/form-data"; this.contentLength = params.length;; } } AjaxRequ ...

Is it possible to extract around 10 variables from a JavaScript code, then display them on a webpage after execution?

I have just completed writing a Javascript code with around 3,000 lines. This code contains over 60 variables, but there are a few specific variables that I would like to display on my main HTML page. These variables include: totalTime longitudinalAcceler ...

What is the process of generating a multi-dimensional JavaScript object using PHP?

Is there a way to transform a PHP array into a multi-dimensional JavaScript object? I have a PHP array shown below that I would like to convert into a JavaScript object: $arrCat = array(); $arrCat['vehicles']['id'][0] = 2; $arrCat[&ap ...

JS Code: Develop a function that generates a distribution analysis of an array

I have been working on a function that calculates the frequency distribution of an array. The aim is to output an object in which the keys represent the unique elements and the values show how frequently those elements appear. Here's the code I' ...

Optimizing the display of multiple list items using Javascript for two separate UL elements on a single webpage

How can I display a maximum of 5 list items in two separate UL elements on the same page and hide the rest? Users should be able to see more items by clicking a dynamic "See more" element created by JavaScript. Below are the UL elements I want to work wit ...

Playing sound files on Angular using Howler.JS

I am currently trying to incorporate the ability to play an mp3 file within a Cordova + Ionic hybrid app. The sound file is located at: www/sounds/dubstep/sound.mp3 I am attempting to play the file from a service placed in /www/scripts/services/global.j ...

Achieve the deliciousness of delect functionality using jQuery with these simple steps

Hi, I have a Bootstrap form that is dynamically appended by jQuery when clicking a button. I would like to have the functionality where clicking on a trash icon deletes the form from the frontend. Attached below is a screenshot of the form that I want to d ...

Javascript is responsible for causing a div to become stuck in a loop of alternating between

My current challenge involves a JavaScript function that manipulates boxes by toggling classnames. The strange issue I'm facing is that the correct classes are being set at the correct times, but the div keeps alternating between the original class an ...

jQuery ceases to function once AJAX content is loaded

Exploring Options for Flexible Data Display I'm currently in the process of building a webpage that allows users to choose between different layouts for loading data. This includes the option to display data in either a list format or a card interfac ...

The scope of this variable in Node.js results in an undefined response

Have you ever noticed the difference in behavior when executing JavaScript code in Google Chrome's console compared to running the same logic in a file using Node.js? function foo() { console.log( this.bar ); } var bar = "global"; foo(); In Chr ...

Implementing the OnClick method for the button component

After successfully creating a reusable button component, I now want to assign different onClick links to each Button component. How can I achieve this? import styled from 'styled-components' const Button = styled.button` background: #0070f3; ...

Effortless Ways to Automatically Accept SSL Certificates in Chrome

It has been quite some time that I have been attempting to find a way to automatically accept SSL certificates. Unfortunately, I haven't had any success yet. The scenario is this: I am working on selenium tests and every time I run the test on Chrome, ...

Retrieve the information sent back by AngularJS and pass it to a JavaScript function

I am working on a form using AngularJS to create a new object, which is returned as "marker." $scope.createMarker = function() { $http.post('/markers/create', $scope.marker) .success(function(data) { }) .error(funct ...

Consider pushing items onto an array only once when the condition is met, instead of adding to the array every

I have been tasked with importing Excel files containing customer orders into my web application. The process involves converting the data in the file into an object of arrays, where each array represents a row from the Excel sheet. Once the data is impor ...

Trying to bring in components from directories above

I'm currently facing an issue with importing components from a parent directory into my project. My goal is to be able to use these components across multiple projects, which seems like the most straightforward approach. However, when I attempt this, ...

Using whitespace to format a document.write in JavaScript

I'm in the process of creating a dynamic table using JavaScript and a set of objects. I've managed to structure it, but now I require some extra white space between them, almost like tabbing them out. How can I achieve this efficiently with my cu ...

Accessing a JBoss Web Service using JavaScript (AJAX) - A Comprehensive Guide

After experimenting with JBOSS's Web Services, I have successfully set up the following: http://127.0.0.1:8080/IM/TestService?wsdl My next challenge is to call Web Methods from that Web Service using JavaScript. For example, if there's a web m ...

JavaScript: Locate a property and its corresponding value within a JSON object

Dealing with a JSON object that varies in structure, but always contains a key. Any suggestions on how to extract this information? For example: "Records": { "key": "112" } Or "Records": { "test": { "key": "512" } } Or even within ...

script for a background image that is centered and covers the entire screen

I have created a function to dynamically adjust the size of an image based on the window dimensions. However, there are times when the image does not fully expand to fill the width of the screen and instead remains constrained by its height. Any insights o ...

An interactive 3D model emerges against a sleek ebony backdrop on my online platform

I stumbled upon a three.js 3D object featuring a unique touch - a 404 text with a floating orb replacing the zero. Upon importing its code, it rendered successfully, albeit against a black background. Despite my efforts to tweak values and apply background ...