Discovering a Subarray within an Array

I have an array called 'array'

array = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]];

and I am trying to find the index of the subarray

[1, 2, 3, 4]

However, every time I attempt this, it returns -1 instead of the expected value of 0.

This is what I have tried so far:

array.indexOf(1, 2, 3, 4);

I understand that the issue lies with the commas in the subarray I am searching for.
Can someone please advise me on how to resolve this problem?

Answer №1

One way to quickly compare arrays is by converting them into strings and then comparing those strings:

var array = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]];

var target = [9, 10, 11, 12].toString();
for(var i=0; i<array.length; i++) {
   if(target === array[i].toString()) break;
}

if(i >= array.length) {
    console.log("Item not found");
} else {
    console.log("Found at position " + i);
}

Link to example

Answer №2

One issue arises when JavaScript uses == to compare arrays and it doesn't function as expected. To solve this problem, you need to create your own array equality checker (refer to How to check if two arrays are equal with JavaScript?). Then iterate through the array and verify each sub-element to see if it matches the one you're looking for.

function arraysEqual(a, b) {
    if (a === b) return true;
    if (a == null || b == null) return false; 
    if (a.length != b.length) return false;

    // If order of elements inside array is not important, sort both arrays here.

    for (var i = 0; i < a.length; ++i) {
        if (a[i] !== b[i]) return false;
    }
    return true;
}

var haystack = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]];
var needle = [1, 2, 3, 4];
var i = 0;

for(var sub in haystack) {
    if(array_equal(sub, needle)) { // found it
        return i;
    }
    i++;
}

if(i >= haystack.size) // didn't find it
    i = -1;

return i; // return the index of the found needle-array

Answer №3

Here's a straightforward implementation for string matching using only built-in methods and no additional variables:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
 .map( /./.test, RegExp( "^"+ [9, 10, 11, 12]+"$"  )).indexOf(true); // === 2

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

Tips for Allowing Multiple Exports in a Vue 3 Single File Component

I am currently working on a Vue3 Single File Component for a customized list. Within this single file component, my objective is to export the main default Vue component along with an enum that declares the type of list it represents: child: <template& ...

What is the best way to generate a ul-li structure using JSON input and jQuery?

There is a JSON variable present: var links=[{"text":"Home","href":"http://home.com","icon":"fas fa-home","target":"_top","title":"My Home","children":[{"text":"home2","href":"home2.com","icon":"fas fa-chart-bar","target":"_self","title":"home2","category ...

What are the steps for performing a self-triggered AJAX post request?

I have been exploring self-invoked functions and recently used an http.get function to retrieve data from a JSON file like this: var Callmodule = (function(){ var urljsonEntrata= "modello.json"; function getmodules(){ var req = $.ajax({ url: ...

SyntaxError: Unexpected token : error caused by an invalid label

When attempting to perform an ajax call, I receive a JSON object as a response: { id: 6, success: "true" } The ajax call in question is the following: window.foobar = function(foo){ $.ajax({ url: "http://foobar.com/sites/foo/", ...

"Encountering a hiccup with Axios while making a GET request in a React

I've been attempting to retrieve data from the API using an axios get request, but I keep encountering an error. The error message reads as TypeError: this.setstate is not a function. Despite looking at various solutions for similar issues, most of th ...

Combining Mocha, BlanketJS, and RequireJS has resulted in the error message "No method 'reporter'."

While using Mocha with RequireJS, my tests are running smoothly. However, I encountered an issue when trying to incorporate blanket code coverage. The error Uncaught TypeError: Object #<HTMLDivElement> has no method 'reporter' keeps popping ...

Ordering tables according to the last column using jQuery

Despite trying various solutions provided in other discussions, I have been unable to get the table to display in descending order based on the Weight Score column. Here is a reference of the table: <table align="center" border="1px" cellpadding="5" id ...

Changing a single state in React results in the modification of both states simultaneously

Whenever I attempt to modify one state, I find that another state is inexplicably changing as well. I've scoured my code for the issue but can't seem to pinpoint it. What steps should I take next? Here's the snippet of code in question: impo ...

Find and return a specific record from MongoDB if it matches the exact value

model.js import mongoose from 'mongoose'; const { Schema, Types } = mongoose; const participants = { user_id: Types.ObjectId(), isAdmin: Boolean } const groupSchema = new Schema({ id: Types.ObjectId(), // String is shorthand for {type: St ...

My node.js and express application is encountering an issue where it is failing with an error indicating that a variable has not been

Currently in the process of understanding how node.js and express operate. I've successfully extracted data from my mongo database... and now I'm experimenting with transferring data between my router code and views. The locations.js file within ...

Expecting a volumetric result can be deceiving when dealing with objects that have three flat

The problem at hand: When subtracting a cube from a sphere, an interesting result occurs where the z axis maintains its volume while the y and x axes create flat disks. This peculiar outcome is puzzling to me as I utilize the typical subtraction method wi ...

Retrieve chunks from a numpy array

In my text file, I have a table with tab-delimited data. Year TMAX1 TMAX2 TMAX3 TMAX4 TMAX5 TMAX6 TMAX7 TMAX8 TMAX9 TMAX10 TMAX11 TMAX12 TMIN1 TMIN2 TMIN3 TMIN4 TMIN5 TMIN6 TMIN7 TMIN8 TMIN9 TMIN10 TMIN11 TMIN12 ...

Interval set does not refresh an integer

I'm struggling with a function that is supposed to show the number of milliseconds elapsed since Midnight on January 1st, 1970. I've been trying to use setInterval to update the integer every second or millisecond, but it doesn't seem to be ...

Animating color on a JSON model when loaded in three.js

Can you animate the colors of a loaded JSON model in three.js? In my code, I used the ObjectLoader() to render the model. Now, I want to be able to animate the color of the model after it's been loaded. var objectLoader = new THREE.ObjectLoa ...

Using AJAX and JQuery to automatically refresh a webpage on a scheduled interval

I am attempting to automatically refresh a page every 5 seconds with updated data from an SQL Server. Below is my code snippet: @model Test.Data.Domain.ManufacturingCdMachine @{ ViewBag.Title = "Rimage Details"; ViewBag.JobId = Model.CurrentManufa ...

The request for an advertisement was successful, however, no ad could be displayed as there was insufficient ad inventory available. Please handle the situation appropriately with the

Using react-native, I am trying to incorporate ads into my app but encountering an error. Despite attempting various solutions, nothing seems to work. It appears that the issue may lie with the AdMob Android SDK. While I have reviewed SDK videos related to ...

jQuery: extracting unique content from DOM elements using filter/get/select techniques

After retrieving an XML document using AJAX, I'm faced with the challenge of filtering out duplicate <category> elements based on their unique HTML content. In the XML data, there are four <category> elements: 2 x DVR, 1 x Alarms, 1 x Bull ...

PHP - troubleshooting the issue of unset array not functioning within a foreach loop

I'm currently working with an array called $positions that contains various items and I am encountering a problem with removing specific items from it. Here is my code: foreach ($positions as &$position) { if ($position['date'] == ...

Encountered an Unexpected Token on Heroku: ??=

2021-12-02T02:42:45.888858+00:00 app[worker.1]: /app/node_modules/discord.js/src/rest/APIRequest.js:33 2021-12-02T02:42:45.888875+00:00 app[worker.1]: agent ??= new https.Agent({ ...this.client.options.http.agent, keepAlive: true }); 2021-12-02T02:42:4 ...

Utilizing the classList property with elements that are hidden from view

How can I use JavaScript to toggle between classes? I can't seem to understand why an element that is set to display: none; is unable to receive a class using classList. In simpler terms, if I define #div1{ width: 25%; background-color: #000000; ...