Tips for discovering the index value of a two-dimensional array in JavaScript

I am working with a 2D array that is structured as follows:

var numbers=[[1,2,3,4,5],[6,2,3,5,5],[9,8,3,4,9]]

Is there a way to determine the index value of elements in this two dimensional array?

Answer №1

Here is a useful alternative:

let key = 5;
array.forEach(function(item, index){
  item.forEach(function(subItem, subIndex){
     if(subItem === key){
        console.log("Index of parent item: " + index);
        console.log("Index of child item: " + subIndex);            
     }     
 })

});

Answer №2

function searchArray(arr, element) {
    var occurrences = [];
    for(var i = 0; i < arr.length; i++)
        for(var j = 0; j < arr[i].length; j++)
            if(arr[i][j] == element)
                occurrences.push(i+"*"+j);
    return occurrences;
}

Testing the function with numbers array:

var numbers = [[1,2,3,4,5],[6,2,3,5,5],[9,8,3,4,9]];
var results = searchArray(numbers, 4);
console.log("found " + results.length + " occurrences: " + results);

found 2 occurrences: 0*3,2*3

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

Is it possible to livestream game server chat on a website?

Playing Swat 4 v1.0 multiplayer has been a blast for me. Recently, I came across a website called www.houseofpain.tk that displays a live server chat viewer. I'm really interested in adding this feature to my own gameserver. I believe the other site u ...

Navigating between Vue Router pages triggers multiple events within the mounted() lifecycle of VueJS

Currently, I am immersed in a project using Electron with a Vue CLI setup and the Vue CLI Plugin Electron Builder. The overall functionality is working perfectly fine except for a peculiar bug that has recently surfaced. The issue arises when navigating b ...

Is it normal for e.target.result to only work after two or three tries?

Attempting to resize an image on the client side before sending it to the server has been challenging for me. Sometimes, the image does not align correctly with the canvas used for resizing. I have noticed that I need to send the resized image at least tw ...

Continue to cycle through an array in a recursive manner while keeping its original size intact

I am currently working on solving a programming challenge in Java, but I want to approach it as a more general problem rather than being specific to one language. The requirements for the function I am trying to create are: Only the values inside the ar ...

Store two select values from PDO query in an array

Currently, my PDO looks like this: $id = 1; $title = 'resourceName'; $url = 'resourceURL'; $result = array($title => $url); include('../dbconnect.php'); $pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $d ...

Experiencing issues with the session not functioning properly on the login page

After setting up Centos 6.4 on my HP Server with PHP 5.3.3, Apache 2.2.15, and Mysql 5.1.69, I encountered login issues where it always fails. Here is the source code: index.php <? include "functions.php"; start_session(); session_destroy(); start_ ...

Ways to resolve nested structure issues within a bookshelfjs transaction

I'm looking to optimize my code by updating multiple tables in a database using a single bookshelf transaction. I'm relatively new to node.js and struggling with promises, resulting in a messy nested structure. Any suggestions on how to refactor ...

Utilizing Node.js and Express to call a function twice - once with the complete req.body and once with an empty body

Trying to articulate this may be a bit challenging, but I'll give it my best shot. I have an iOS app and Android app that both access the same node.js app through their respective web views. The iOS version is able to open the node.js app without any ...

Error: JSON at position 1 is throwing off the syntax in EXPRESS due to an unexpected token "

I'm currently utilizing a REST web service within Express and I am looking to retrieve an object that includes the specified hours. var express = require('express'); var router = express.Router(); /* GET home page. ...

Trouble with submitting a form and showing a success message in AngularJS version 1.6.8

My query submission form consists of fields for name, email, and the actual query. The component includes a controller function with a submit function to handle form submission. To submit user input and display a success message upon submission, I utilize ...

Execute npm build in sbt for play framework

Exploring sbt/play configuration is a new challenge for me. Working with play 2.3.8 to host my javascript application, my project utilizes: .enablePlugins(SbtWeb) .enablePlugins(play.PlayScala) .settings( ... libraryDependencies ++= WebDependancies :+ ...

What is the best way to include several components in a PickerView?

I have a question regarding adding multiple components to a UIPickerView. Currently, I am using NSMutableArray to populate one component successfully, but I am unsure how to go about populating the others. Additionally, I need to be able to update the va ...

Using Javascript to update various element styles using their corresponding IDs

I am currently working on implementing a dark mode feature and I am encountering an issue when trying to change the CSS of multiple elements at once. This is my JavaScript code: var elem = document.getElementById('fonts'); for(var i= ...

Keys stored in the local storage lists

Can someone guide me on how to format the keys as numbers (1, 2, 3...) in this code snippet: <input type='text' id='provedor' /> <input type='text' id='login' /> <input type='text' id=&a ...

Modify parameters variable when searching by utilizing bootgrid along with structured-filter

I have implemented both https://github.com/evoluteur/structured-filter and to develop an advanced search functionality using ajax/php. Initially, the code is functioning correctly and retrieves data from the php file. However, I am facing difficulties wh ...

Struggling with PHP variables and AJAX JavaScript

Hey everyone, I've made some edits and have a new question regarding a similar issue. On test.php in my Apache server, I have a PHP script that connects to a database and retrieves data from a table. <?php $con = mysqli_connect("localhost", "user" ...

Vuejs unstyled content flash

I encountered an issue while loading a page with Vue. Initially, I am able to access variables like @{{ value }} but once the page is fully loaded, the variable becomes invisible. How can I resolve this issue? I have already included Bootstrap and all scri ...

Tips for increasing the number of pixels in the current position of an element?

I need to shift an image to the right by adding pixels to its current left position. The challenge arises when the image, positioned absolutely, goes back to its nearest relative parent (the container) and creates a strange visual effect. Within my flex c ...

Java: Separating pairs in an Array

I'm currently stuck on a project where I need to write a Java program that accepts ten values from a user and stores them in an array. The program should then add up all the numbers in the array and display the result to the user. (Understood.) Howev ...

Parsing JsonArray elements in Android

I need help retrieving the name and id attributes from this JSon Array: Click here for JSON link Unfortunately, my current code is not working. I am receiving the following error message: org.json.JSONException: Value [{"id":0,"name":"Alsópetény"}] at ...