Locating the index of the initial duplicate in an array using Javascript


    const numbers = [2, 4, 5, 2, 3, 5, 1, 2, 4];

I’m looking to write a function called indexOfRepeatedValue (array) that utilizes the numbers stored in the provided variable. The function should create a variable called firstIndex. Within a for loop, determine which number repeats first and assign its index to firstIndex. Finally, log this variable to the console beyond the for loop.

This initial idea isn’t working as intended. I could use some guidance or advice on how to proceed. Any help would be greatly appreciated!

const numbers = [2, 4, 5, 2, 3, 5, 1, 2, 4];

function indexOfRepeatedValue(array) {
  let firstIndex;
  for (let i = 0; i < array.length; i++)
    if (firstIndex.indexOf(array[i]) === -1 && array[i] !== '');
  firstIndex.push(array[i]);
  return firstIndex;
}

console.log(
  indexOfRepeatedValue(numbers)
)

Answer №1

To begin, create an array called firstIndex: let firstIndex = [];

Ensure that the variable i is within the scope you have defined using let.

Remember to end each statement with a semicolon to prevent the loop from moving to the next line prematurely.

Then, find and return the first number in the new array that matches another number.

Keep in mind that in JavaScript arrays start at index 0, so the result will be 3 because the second occurrence of number 2 is in the 4th position.

I have tried to maintain the structure of your code as closely as possible.

const numbers = [2, 4, 5, 2, 3, 5, 1, 2, 4];

function indexOfRepeatedValue(array) {
  let firstIndex = [];
  for (let i = 0; i < array.length; i++) {
    if (firstIndex.indexOf(array[i]) !== -1) { // duplicate found
      console.log("found",array[i], "again at index", i)
      console.log("The first occurrence of this value is at index",numbers.indexOf(array[i]))
      
      return i; // stop and return once found
      // use `return numbers.indexOf(array[i])` if you want the index of the first duplicate   
    }
    firstIndex.push(array[i]); // no duplicate found yet
  }
  return "no duplicates found"
}

console.log(
  indexOfRepeatedValue(numbers)
)

There are multiple approaches to solving this problem.

JavaScript: How to find first duplicate value and return its index?

Answer №2

To efficiently find the index of a repeated value in an array, you can create an object to store the index of each element and return early if the index already exists.

function findIndexOfRepeatedValue(arr) {
    let idx = {};
    for (let i = 0; i < arr.length; i++) {
        if (idx[arr[i]] !== undefined) return idx[arr[i]];
        idx[arr[i]] = i;
    }
    return -1;
}

const elements = [2, 4, 5, 2, 3, 5, 1, 2, 4];
console.log(findIndexOfRepeatedValue(elements));

Answer №3

To begin, start by setting up the variable firstIndex:

let firstIndex = [];

The next step is to locate the index of each repeated element using the following code:

if( array.slice(0,i).includes(array[i]) ) {
    firstIndex.push( i );
}

If you are looking for the absolute first index of a repeat, simply return:

return firstIndex[0];
//Keep in mind that if your goal is solely to find the first index, there is no need for the firstIndex variable or to iterate through the entire loop.

If you require all indices of repeated elements:

return firstIndex;

const numbers = [2, 4, 5, 2, 3, 5, 1, 2, 4];

function indexOfRepeatedValue(array) {
  let firstIndex = [];
  for (let i = 0; i < array.length; i++)
    if( array.slice(0,i).includes(array[i]) ) {
      firstIndex.push(i);
    }
  return firstIndex[0];
}

console.log(
  indexOfRepeatedValue(numbers)
)

NOTE

Another approach is to utilize Array#map to obtain the index of repeated values and then use Array#filter to retain only those indices, where the first instance can be accessed with [0].

const numbers = [2, 4, 5, 2, 3, 5, 1, 2, 4];

const indexOfRepeatedValue = arr => 
    arr.map((a,i) => arr.slice(0,i).includes(a) ? i : -1)
    .filter(i => i > -1)[0];
    
console.log( indexOfRepeatedValue( numbers ) );

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

Strategies for managing callback responses within Ejs

I'm facing a challenge in my Node.js application where I need to execute an async function within Ejs code and display the result. Here's what I've attempted: <ul> <% setTimeout(function () { %> <% supplies = [1, 2, 3, 4]; %& ...

Monitoring Changes in Input Values within PHP foreach Loop using jQuery

In my PHP code, I have a foreach loop inside a form that populates input values from a database. Each input has a unique ID generated based on the loop index. <form class="form-horizontal"> <?php $count = 0; foreach ($value as ...

What is the proper way to include redirect_uri in next-auth?

I utilize next-auth for authorization import NextAuth from 'next-auth'; export default NextAuth({ providers: [ { id: 'reddit', name: 'Reddit', clientId: process.env.CLIENT_ID, ...

I would like to terminate the property when processing it on a mobile device

<div class="col-sm-24 embed-responsive"> <iframe width="100%" src="http://www.youtube.com/embed/${item.snippet.resourceId.videoId}"></iframe> </div> .embed-responsive iframe { height: 185px; margin-top: -4%; paddin ...

After a span of two minutes, the Node.js and Express server terminates the connection

I am currently working with Express 4.X and Node.js 0.12. One of the routes in my application is responsible for uploading and processing files. However, I have encountered an issue where some file uploads are taking longer than the default 2-minute timeo ...

Retrieving data with JQuery when encountering an XHR error

When I send a jQuery AJAX request and receive a successful response, I am able to retrieve my JSON data. However, if the response code is anything other than 200, I am unable to access the data in the jQuery callback function. This data is crucial as it co ...

Steps for implementing "show less" and "show more" functionality in the cells of a reactive table within a Meteor

customTableSettings : function () { return{ rowsPerPage: 5, showNavigation: 'auto', showColumnToggles: false, fields: [ {key: 'para',label: 'Para',sortable: false}, { ...

How to Send Data to views.py in Django Using JavaScript Onclick Event?

I have some knowledge about using ajax with JavaScript to send data to views.py, but I am struggling to successfully implement it. My goal is to trigger the onclick event on an image to send a certain value to views.py when clicked. Below is the content ...

Rotation Ensuring a Seamless Transition to a Specific Angle

I'm currently trying to figure out how to rotate an object at a speed of 160 degrees per second, gradually slowing down until it comes to a stop at a specific angle. For instance, if the target angle is set to 30 degrees, the object should spin quickl ...

Encountering the "Variable is not defined" error even when the variable has been previously defined. Currently working with EJS and Node

38| <h2 class="card-activity"> 39| <!-- Display Activity --> >> 40| <%= data.activity %> 41| </h2> 42| <div class="card-info"> 43| ...

Using Ramda, learn how to transform a flat list into a hierarchical one

Looking to transform the given list into a hierarchical structure with nested children fields. The 'parentId' attribute has been omitted for clarity, as it will be used in the transformation process using Ramda's immutable behavior. const x ...

Set the JavaScript array variable equal to the value of the input text field containing a JavaScript array

Currently, I am attempting to populate location data for Google Maps initialization. I have tried assigning an HTML input field with a JavaScript array format in order to use it for Google Maps, but unfortunately, my attempts have been unsuccessful. Here i ...

Mobile device experiences shader malfunction

On my laptop, this shader works perfectly fine. However, I'm facing issues on mobile devices and suspect that it might be related to precision settings. Here is the error message I'm encountering: THREE.WebGLProgram: shader error - 0 35715 fals ...

Obtaining the mouse position in JavaScript in relation to the website, preferably without relying on jQuery

I came across this code snippet on Ajaxian, but I am having trouble using cursor.y (or cursor.x) as a variable. When I call the function with it that way, it doesn't seem to work. Could there be a syntax issue or something else causing the problem? f ...

Vue.js does not seem to be properly assigning attributes that are declared within the data object array

Trying to get a hang of vue.js and looking to create dynamic product cards using it: This is the snippet from my HTML file: <div id="app"> <card v-for="products in product" :productname="product.productname"></card> </div> Here&a ...

Use the jQuery .GET() method two times to retrieve data and obtain the outcomes

My code involves making a series of GET calls where the returned data from one call is used in another call before returning the final results. However, I want to ensure that my program waits until all the data is retrieved. This is what I have come up wi ...

Is there a way to modify the existing JSON format?

After receiving a JSON response, I used the code snippet result = JSON.parse(result.value); to parse it. The JSON response I received was: {"name":"For ","children":["{ \"name\":\"sxsm cnklsd\"}","{ \"name\":\"smd csdm&b ...

Node.js Express refuses to serve .js files with absolute URLs

I have encountered a perplexing issue with two files located in /public/widget, namely help.html and help.js http://localhost:8084/widget/help.html When entered into the address bar, it functions normally However, when attempting to access http://local ...

Adjust the stacking order of bars in a vertical chart and exclude negative values with Vega-Lite

I am utilizing this chart as a guide for my current project Explore Vega Editor here https://i.sstatic.net/VGOee.png Is there a way to rearrange the order of the 'Measure' while keeping 'Measure 1' at the top, disregarding its negati ...

Suggestions for relocating this function call from my HTML code

I have been working on updating a javascript function that currently uses an inline event handler to a more modern approach. My goal is to eliminate the unattractive event handler from the actual HTML code and instead place it in a separate modular javascr ...