JavaScript: Determine the index of matching elements in two arrays

Here is a code snippet I am working with:

function findMatch(array_1_small, array2_large) {
var ary = new Array();
for(i = 0;i < array2_large.length; i++)
{
  for(z = 0; z < array_1_small.length; z++)
  {
    if(array2_large[i] == array_1_small[z])
    {
     var idx = array2_large.indexOf(array2_large[i]);
      ary.push(idx);
    }
  }

}
return ary;
}

The code operates on the following arrays:

var all_SMS_TO = ["0861932936", "0871355066", "0874132026", "0872908445", "0874132026"];
var all_FORM_NUMBERS = ["", "", "", "", "", "", "0871355066",""];

Its main function is to identify matches and return their indices in the 'all_form_numbers' array.

When I run the code using this setup:

var a = findMatch(all_SMS_TO, all_FORM_NUMBERS);
console.log("Match Found " + a);

I receive the output:

Match Found: 6

This result is accurate. However, when I modify the 'all_form_Numbers' array as follows:

var all_FORM_NUMBERS = ["", "0871355066", "", "", "", "", "0871355066",""];

The resulting output becomes:

Match Found: 1,1

I am seeking assistance to make the output display as:

Match Found 1, 6.

Any help would be greatly appreciated. Thank you.

Answer №1

Give this a shot:

function checkMatch(arraySmall, arrayLarge) {
var resultArray = new Array();
for(indexLarge = 0; indexLarge < arrayLarge.length; indexLarge++)
{
  for(indexSmall = 0; indexSmall < arraySmall.length; indexSmall++)
  {
    if(arrayLarge[indexLarge] == arraySmall[indexSmall])
    {
      resultArray.push(indexLarge);
    }
  }

}
return resultArray;
}

Answer №2

When you execute

var idx = array2_large.indexOf(array2_large[i]);

you are actually searching for the index of the value 0871355066 in the array named array2_large twice. The indexOf method returns the position of the first occurrence of a specified value.

This explains why you see the index value 1 appearing twice since it represents the index of the first occurrence.

To solve this issue, simply push the variable i's value into the ary array. This value already corresponds to the index value of array2_large within the loop.

function findMatch(array_1_small, array2_large) {
var ary = new Array();
for(i = 0;i < array2_large.length; i++)
{
  for(z = 0; z < array_1_small.length; z++)
  {
    if(array2_large[i] == array_1_small[z])
    {
      ary.push(i);
    }
  }

}
return ary;
}


var all_SMS_TO = ["0861932936", "0871355066", "0874132026", "0872908445", "0874132026"];
//var all_FORM_NUMBERS = ["", "", "", "", "", "", "0871355066",""];

var all_FORM_NUMBERS = ["", "0871355066", "", "", "", "", "0871355066",""];


var a = findMatch(all_SMS_TO, all_FORM_NUMBERS);
console.log("Match Found " + a);

Answer №3

To solve the problem, simply ensure that you are pushing the index i in the code below. You may also choose to create an array by declaring it as var res = [];

function findMatch(arraySmall, arrayLarge) {
  var res = []
  for (var i = 0; i < arrayLarge.length; i++) {
    for (var j = 0; j < arraySmall.length; j++) {
      if (arrayLarge[i] === arraySmall[j]) {
        res.push(i);
      }
    }
  }
  return res;
}

Answer №4

To achieve a runtime complexity of O(n+m), one can solve this issue by initially creating a lookup table of positions. Then, each element from the first array is mapped to all positions and these indices are collected in a Set to retain only unique values.

Give this solution a try:

var all_SMS_TO = ["0861932936", "0871355066", "0874132026", "0872908445", "0874132026"];
var all_FORM_NUMBERS = ["", "0871355066", "", "", "", "", "0871355066",""];

function findMatch(array_1_small, array2_large) {
    var positions = Array.from(array2_large.entries()).reduce((acc, t) => {
        var index = t[0]
        var element = t[1]
        if (!acc.hasOwnProperty(element)) {
            acc[element] = []
        }
        acc[element].push(index)
        return acc
    }, {})
    var result = new Set()
    array_1_small.forEach(x => {
        if (positions[x] === undefined) {
            return
        }
        positions[x].forEach(index => result.add(index))
    })
    return Array.from(result)
}

console.log("Found a match: " + findMatch(all_SMS_TO, all_FORM_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

Utilize the size of the array as a variable

I have a question regarding the use of the length of an array as an integer value in JavaScript. Here is the code snippet: var counter = 0; var bannerLinks = document.getElementsByClassName("bannerlink"); var linkCount = bannerLinks.length; va ...

Accessing values from nested arrays in PHP arrays

I am working with an array in PHP: Array ( [1] => Array ( [DeviceName] => Device1 [DeviceId] => 0x0000001530A1B380 [state] => 0 ... ) [2] => Array ( [DeviceName] => Device2 ...

How to locate the index of a specific item or multiple items within a JsonArray?

Can you help me determine which city is closest to Vancouver: Victoria, Washington or Texas? Once I find the shortest distance, how can I identify which destination address this value corresponds to? { "destination_addresses" : [ "Victoria, BC, C ...

A guide to updating location data with Selenium in Python

I'm attempting to change my location using Python's Selenium package. Despite trying various code snippets, I have been unsuccessful in altering my location from showing as Germany to United Arab Emirates. Below is the code snippet I am currentl ...

Having trouble attaching a function to a button click event

My viewModel includes a function: function resetForm(){ loanSystem("lis"); status(""); processor(""); fileType("funded"); orderDate(""); loanNumber(""); team(""); borrower(""); track ...

Send data from JavaScript variables to PHP script

I've been trying to figure out how to pass variables from a js function to my database using php, but I've hit a roadblock. Any suggestions on how I can resolve this issue would be greatly appreciated. <html xmlns="http://www.w3.org/1999/xhtm ...

Transmitting information together with FormData as a single entity through AJAX

I'm attempting to transmit a FormData within a JSON array to an AJAX script: $('#form').submit(function(e) { e.preventDefault(); let formData = new FormData(this), data = {'action': 'insert', 'data& ...

Activating a switch to execute a PHP code that displays a JavaScript code

At the conclusion of the button's click event, the following JavaScript code is executed: xmlObj.open ('GET', /ajax.php, true); xmlObj.send (''); } This will trigger the php script ajax.php located in the root directory: <?ph ...

Dynamically add a Font Awesome icon to the background of an input text field with React and react-fa

Utilizing ReactJs and react-fa to access Font Awesome icons, I am attempting to dynamically place one of the icons inside a text input. The following is my code snippet: import React, { Component } from 'react'; import PropTypes from &a ...

What's the best way to convert the elements in my array to integers?

My goal is to populate an array with integers, and I need detailed explanations for each step. Picture this: I have a suitcase that I want to fill with items. Here's what I've done so far: suitcase = [] #Initially empty suitcase.append("sungla ...

Struggling to retrieve Codemirror textarea values across multiple elements with JavaScript/jQuery

I've been struggling to retrieve the values from my textarea codemirror in order to send them as JSON to the server for saving after editing. Unfortunately, I am unable to select the ELEMENT...I even attempted to grab the element by its id...with no s ...

Having trouble establishing a connection to SQL Server with tedious in Node.js

Trying to connect to the SQL Server "SQL.SCHOOL.EDU\STUDENTSQLSERVER,4500" from my school has been a real challenge for me using tedious. I am currently working on setting up a connection between my express back end and react front end. For now, I am ...

Utilizing an iPad to control and modify the content displayed on an external monitor

I am uncertain about the exact scope of this project and would appreciate input from those with prior experience. The project involves creating a mobile site that will act as a framework for displaying content. The 'app' will feature a simple li ...

Tips on leveraging LocalStorage to update state in ReactJS

In my code, an array fetches API data each time componentDidMount() is called. Within this array, each element contains an object with a default boolean value of true. An onClick function toggles the boolean value of a specific element to false when clicke ...

Following its repair by my factory service, the data is now being shown complete with obvious HTML tags

After retrieving my data from a factory service in the form of a json_endoded array, I store it in a Javascript variable to be used as a template. When this template is displayed on a page, it appears with HTML tags intact: Some text here<br/><br ...

Upgrading from Asp.Net Core 2 to .Net 6 caused issues with XMLHttpRequest for me

Hello everyone, I recently upgraded my ASP.Net Core 2 MVC app to .Net 6, and ever since then, I've been experiencing a strange issue. The XMLHttpRequest responses I receive are always empty, showing "{}" or [{},{},{},{}] for arrays, even though the ba ...

What is the process for inserting values into an array and map in a SQL Databricks database?

I have successfully created a schema in Databricks, but I am facing difficulty in inserting data into the array and map fields. I have been unable to find any information related to SQL specifically as most resources focus on Python and Scala. I am specifi ...

Access the socket.io administrator portal

Every time I attempt to connect to Socket.IO Admin UI, this is what unfolds: (https://i.sstatic.net/JYqqf.png) the server code : const io = require('socket.io')(3001,{cors: {origin:["https://admin.socket.io","http://localhost:8 ...

React hook, when not properly called, may result in an error known as

While working on a project with React hooks, I encountered the error message below. Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might ha ...

Changing the value of an input field based on a user's input

Looking to automatically format any input in an input field as currency: <input type="text" value="0,00 EUR" onChange={(e) => { e.target.value = convertToCurrency(e.target.value) }} /> const convertToCu ...