How to locate the duplicate elements within an array using JavaScript

There are two different sets of numbers

Numbers1=[ 0, 1, 2, 0, 2 ];

Numbers2=[ 0, 0, 1, 2, 2 ];

The goal is to determine the index of each element in Numbers2 from Numbers1 and create a new array like [0,3,1,2,4];

If you would like to see the code I wrote, check it out here. However, please note that it currently does not account for duplicate values in the arrays.

var index = [];
for (i = 0; i <= Numbers2.length - 1; i++) {
  index.push(Numbers1.indexOf(Numbers2[i]));
}

Answer №1

To find the second element and all repeating elements after the first index, use the fromIndex argument in the Array#indexOf method to specify the starting index for the search.

// Use a reference object to set the from index for duplicates
var ref = {};

var index = [];

for (i = 0; i < arr2.length; i++) {
  // Set the from index using the reference object, if not found, set as 0
  var i1 = arr1.indexOf(arr2[i], ref[arr2[i]] || 0);

  // Push the index into the array
  index.push(i1);

  // Update the from index for the current element
  ref[arr2[i]] = i1 + 1;
}

var ref = {};

var arr1 = [0, 1, 2, 0, 2],
  arr2 = [0, 0, 1, 2, 2];

var ref = {};

var index = [];

for (i = 0; i < arr2.length; i++) {
  var i1 = arr1.indexOf(arr2[i], ref[arr2[i]] || 0);
  index.push(i1);
  ref[arr2[i]] = i1 + 1;
}

console.log(index);


Use the Array#map method to generate the index array.

var index = arr2.map(function(v, i) {
  // Find the index of the element, starting the search after a specific index for repeat occurrences
  var i1 = arr1.indexOf(v, this[v] || 0);

  // Update the reference index 
  this[v] = i1 + 1;

  // Return the index value
  return i1;
  // Set this argument as an object for reference to from index
}, {});

var arr1 = [0, 1, 2, 0, 2],
  arr2 = [0, 0, 1, 2, 2];

var index = arr2.map(function(v, i) {
  var i1 = arr1.indexOf(v, this[v] || 0);
  this[v] = i1 + 1;
  return i1;
}, {});

console.log(index);

Answer №2

Here is a JavaScript code snippet that compares two arrays and returns the indexes of common elements:

var arr1 = [ 0, 1, 2, 0, 2 ];
var arr2 = [ 0, 0, 1, 2, 2 ]
var index = [];
var hash = {};
for (i = 0; i < arr2.length; i++) {
  var ind_temp;
  if(arr2[i] in hash){
    //console.log("here");
    ind_temp = arr1.indexOf(arr2[i],hash[arr2[i]] + 1);
    index.push(ind_temp);
    hash[arr2[i]] = ind_temp;
  }
  else{
    ind_temp = arr1.indexOf(arr2[i]);
    index.push(ind_temp);
    hash[arr2[i]] = ind_temp;
  }

console.log(index);

Answer №3

To search through an array and match it with another array, you can use the map function while ensuring the first occurrence is set to undefined. Keep in mind that this method may not be effective if undefined is a value you need to locate.

let updatedArray = originalArray.map(item => {
  if (!item) return undefined;
  let index = secondArray.indexOf(item);
  if (index) secondArray[index] = undefined;
  return index;
})

Answer №4

Here's a helpful solution for dealing with arrays containing only positive numbers:

let copy = originalArr.slice(0); // Create a copy of the original array

let indices = [];

additionalArr.forEach(element => {
    let idx = copy.indexOf(element);
    indices.push(idx);
    if (idx > -1) {
        copy[idx] = -1;
    }
});

console.log(indices);

Answer №5

To achieve this, iterate through arr2 and store the index found in arr1 in a variable. If an element in arr2 matches the previous element, compare it starting from the saved index + 1 using the second parameter of the indexOf method.

var duplicate = [0, 1, 2, 0, 2];
var newiter = [0, 0, 1, 2, 2];
var indexArray = []; // STORED INDEX ARRAY

var newiterSorted = newiter.sort(); // ENSURE NEWITER IS SORTED

var i = -1;
for (var j = 0; j < newiterSorted.length; j++) {

    // Check if current element is different from previous, reset i to -1
    if (j > 0 && newiterSorted[j] != newiterSorted[j - 1]) {
        i = -1;
    }

    // Find index in 'duplicate' array starting from i+1
    i = duplicate.indexOf(newiterSorted[j], i + 1);
    indexArray.push(i);
}

console.log(indexArray);

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

In AngularJS, variables can undergo automatic value changes without any external connections

Within my AngularJS controllers, I have initialized two variables: _this.currentData=new Array(); _this.masterCurrentData=new Array(); Later on, I created a temporary array of objects called tmpDataSort and populated it separately using loops. var tmpDa ...

Retrieving the value of onCheck from the Checkbox/ListItem

Imagine I have a React.Component that displays components from material-ui: {data.map(value => ( <ListItem key={data.indexOf(value)} primaryText={value} leftCheckbox={ <Checkbox onCheck={this.pr ...

Search through an array, identify duplicates, and transfer them into a separate array

I am working with an array of objects containing dates and I am looking to extract objects with the same date values into a new array. Below is the code snippet. var posts = [ { "userid": 1, "rating": 4, "mood": "happy", "date": "2 ...

What alternative methods are available to rename a field that has been returned in mongoose, if at all possible?

I need help with this specific query: MessageModel.find({ conversationId: { $in: ids } }) .sort({createdAt: 'ascending'}) .populate({ path: 'receiver', select: '_id' }) .populate({ path: &a ...

Can preloading data from a website impact the accuracy of my google analytics data?

I am interested in creating a simple script that utilizes AJAX to load the content from each page listed in my main navbar into a hidden div on the current page. My goal is to preload important content and cache it on the user's computer to ensure fa ...

Unable to retrieve button value with material-ui package

My task requires me to retrieve the value of a button, as it contains an ID essential for further steps. Initially, I used a standard button with Bootstrap styling and everything functioned correctly. <button value={row.vacationRequestID} c ...

Discover the nearest class and smoothly expand it with the slideDown function in jQuery

Hey there, I'm working on implementing a "View More" button on my page. The button will reveal another unordered list that currently has the class of "hidden-list". When the user clicks on "View More", I want it to slideToggle the hidden-list element ...

Display the tooltip only when the checkbox is disabled in AngularJS

My current setup includes a checkbox that is disabled based on a scope variable in Angular. If the scope variable is true, the checkbox stays disabled. However, if the scope variable is false, the checkbox becomes enabled. I am looking to implement a too ...

Retrieving a single object in NEXT.JS and MongoDB can be achieved by returning just a single object

Is there a way to retrieve a single object instead of an array from the API? I am specifically looking for just a single "Event" while using MongoDB and Next.js. Currently, I always receive: [{}] But I would like to receive: {} const fetchWithId = (url ...

Problem with ngStyle: Error indicating that the expected '}' is missing

I encountered an error in the Chrome console when trying to interpret the code below: <div [ngStyle]="{'width': '100%'; 'height': '100%'; 'background-size': 'cover'; 'background-repeat&ap ...

How can I feature an image at the top of the page with large 3 and jQuery in FireFox?

I am interested in showcasing a single image at the forefront of the page when it is selected. While there are numerous plug-ins that offer this feature, many come with unnecessary extras like galleries, video support, and thumbnails which I do not requir ...

Nested MongoDB object within multiple arrays

I need help with handling this JSON data structure: { data : { fields_data : [ [ { key1 : val }, { key1 : val } ], [ { key2 : val }, { key2 : val ...

Angular 2: Applying class to td element when clicked

I am working with a table structured like this <table> <tbody> <tr *ngFor="let row of createRange(seats.theatreDimension.rowNum)"> <td [ngClass]="{'reserved': isReserved(row, seat)}" id={{row}}_{{sea ...

What is the best way to assign three different dates in my protractor test?

I am facing an issue with setting random dates in 3 date fields in a row using Protractor. The problem is that Protractor sets the dates too quickly and sometimes assigns invalid dates like: first data: 01/08/1990 (correct) second data: 01/09/0009 (inva ...

Difficulty in obtaining the child index upon clicking

I am currently working on retrieving the index of a child element within a parent element. While following a solution here, I encountered an issue with an infinite loop. This is the code I have written so far: var div = document.getElementById("spans ...

Alter the URL and CSS upon clicking an element

Currently, I am faced with a challenge on my website where I have multiple pages that utilize PHP to include content and jQuery to toggle the display of said content by adjusting CSS properties. However, I am encountering difficulty in implementing this ...

Adjusting the height of a textarea with javascript

I am trying to reset the contents and height of an auto resizing textarea element. My attempts so far include: document.getElementById('textarea').value = ''; As well as: document.getElementById('textarea').attribute(&apos ...

Listening on TCP port for HTML5 Websocket communications

I have a desktop application that is communicating with my asp.net mvc app. The desktop application publishes data on port:10000 which I need to be able to listen to in the browser. Below is the code snippet: <html> <head> <s ...

How can I use regular expressions to locate a React JSX element that contains a specific attribute?

Currently conducting an audit within a vast codebase, my task involves searching for all instances of a component where it is utilized with a specific prop. I believe that using regex could prove beneficial in this situation; however, the challenge lies in ...

Exploring Angular.JS: How to Access Sub-Arrays and Parse Keys

Trying my hand at building something with Angular for the first time, I'm facing an issue with retrieving JSON data. The data is fetched from a SQL database in JSON format and passed to a template using Angular route: .when('/tasks/:TaskID&apos ...