How to locate the position of an element within a multi-dimensional array using TypeScript

My data structure is an array that looks like this:

const myArray: number[][] = [[1,2,3],[4,5,6]]

I am trying to find the index of a specific element within this multidimensional array. Typically with a 1D array, I would use [1,2,3].indexOf(1) which would return 0. However, this method does not work for my situation.

Answer №1

To find the indices of arrays containing a specific value, you can use the following JavaScript function:

const
    findIndices = (array, value) => {
        if (!Array.isArray(array)) return;
        let index = array.indexOf(value),
            temp;

        if (index !== -1) return [index];
        index = array.findIndex(v => temp = findIndices(v, value));
        if (index !== -1) return [index, ...temp];
    },
    data = [[1, 2, 3], [4, 5, 6]];

console.log(findIndices(data, 1));
console.log(findIndices(data, 5));

Answer №2

When dealing with a 2D array, you cannot use indexOf directly as it relies on strict equality and tries to match the target value with elements of outer arrays, resulting in -1 always.

Instead, you can utilize findIndex and includes methods like this:

const myArray = [[1,2,3],[4,5,6]]

let indexFinder = (arr,target) => {
  return arr.findIndex(v=> v.includes(target))
}

console.log(indexFinder(myArray,1))
console.log(indexFinder(myArray,6))

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

What could be causing MS browsers to transform my object array into an array of arrays?

Noticing an interesting behavior with Microsoft browsers especially when dealing with data returned from our product API. It seems that the array of 52 product objects is being transformed into several arrays, each containing only 10 objects. Our error tr ...

Creating a Website that Adapts to Different Browser Sizes: Tips and Tricks

I am currently working on a website that features a video background (mp4 file). However, I noticed that the video appears differently in Chrome, Explorer, and Firefox. In order to ensure compatibility across all browsers, I need to make some adjustments i ...

Exploring the use of index signatures in TypeScript when working with React

I'm struggling to properly implement the index signature in this code. I have an enum and I need to loop through it to display some JSX on the screen. I understand the error message, but I'm having trouble resolving it in my code. The issue seems ...

css problem with scaling in firefox

My goal is to create a website that adjusts its size based on the document size. When the document size is between 0px and 1024px, I want the design to be responsive. This can easily be achieved with CSS media queries. Similarly, when the document size is ...

How to bring in images from the assets folder using React and Typescript

I'm facing an issue where direct image importing is working, but when using object types, it's not functioning properly. Why could this be happening? I am currently working with "react": "^16.12.0" and "typescript": "~3.7.2" // ./src/assets/baby ...

Using recursion in JavaScript to determine if a given number is prime

I am feeling a bit puzzled about how to tackle this issue. My goal is to have all prime numbers return as true, and if not, then false. I noticed that my current logic includes 2, which returns 0 and automatically results in false because 2 has a remainder ...

Is it possible for jQuery to analyze HTML contained within a variable?

Currently, I am utilizing PHP along with an ajax command to retrieve the complete HTML content from an external webpage using the file_get_contents() function in PHP. After storing this HTML in a JavaScript variable, I am curious if it is possible to uti ...

Saving modified input data for submission using Vue

Objective: The main goal is to have a form interface loaded with an object's current data for editing. This allows the user to open a modal with the form already filled out with the existing information, giving them the option to either edit it or lea ...

Fixed-bottom footer in Bootstrap 5 that overlays content

Having trouble creating a fixed footer using the fixed-bottom class in react & bootstrap. The issue is that it's covering some content and I've tried various solutions without success. Any suggestions on how to fix this? (Code and Demo provided b ...

Guide to swapping out the variables "labels" in JavaScript

Here is the object structure: { 'File_12345.ZLM': { MeterID_12345: { BASIC_INFO: [Object] } } } { 'File_678910.ZLM': { MeterID_678910: { BASIC_INFO: [Object], } } } ======================== ...

What is preventing me from adding content to a <p> element?

I'm currently developing a ToDo list web application and I'm working on retrieving the information from 4 text boxes to create the content for each ToDo item. However, when I attempt to link the elements generated from the form, I encounter the ...

How can JavaScript be utilized for connecting to CSS files?

I'm unsure if this is feasible and after a brief search, I couldn't find any information. I am curious to know if it's possible to connect a CSS file using JavaScript? In essence, I would like to invoke a style sheet when I execute a specif ...

What steps should be taken to incorporate that dynamic sliding element (like a sliding screen paper) on the webpage?

When hovering over the leftmost part of the homepage at www.techants.com, a box shifts to the foreground. I examined the code and noticed a reference to something called screen paper. Does anyone know which script is being used for this effect? How can I ...

Unable to employ Javascript while utilizing AJAX within jQuery Mobile

Exploring the potential of Swiper Javascript Api from within Jquery Mobile raises some challenges. The compatibility issues with Ajax in Jquery Mobile complicate the execution of Javascript functions. This becomes evident when examining example source cod ...

Troubleshooting: Issue with AJAX xmlhttp.send() functionality

I'm new to AJAX and have been stuck on the same issue for hours. Here is my script code: <script language='javascript'> function upvote(id ,username) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = fun ...

Tips on maximizing efficiency in number game coding

Seeking to create a number using a specified set of 6+ inputs. For instance, aiming for the number 280 with inputs [2,4,5,10,30,50,66], the desired output format would be something like this: ((2+5) * 4 * 10). Each input number can only be used once per s ...

The quantity of elements stays constant even after adding to them using Javascript

I have implemented a notes list feature that allows users to add notes using an input field. Beneath the notes list ul, there is a message showing the total number of notes: $('li').length. However, I encountered an issue where the count of not ...

Tips for stopping links in iOS web applications from launching in a new Safari tab

I am in the process of developing an HTML application specifically for iPads. To enhance user experience, I have added the web app to the homescreen using the "favorite" option. However, I encountered an issue where every internal URL opens in a new Safari ...

Using TypeScript generics to constrain to either a number or a string

I am working on coding a react input component that accepts a defaultValue parameter of type string | number. This component has a state type matching the type of the received defaultValue; This is my code: type TypeName<T> = T extends number ? "nu ...

"Obtain a DOM element within an Angular directive by using the jQuery find method

When inspecting the DOM, I can see the element anchor tag present but cannot retrieve it using jquery.find(). The console returns a length of 0, preventing me from initializing angular xeditable on that element. angular.module('built.objects') ...