Finding the position of a specific string within a multidimensional array in JavaScript

I have an array that looks like this:

var arr = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]];

var arr2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];

My goal is to retrieve the data[0] of the array containing the value "Mary". In this case, I should get "absent".

Additionally, I want to find the index of the array in arr2 that includes the value "Josh". Therefore, I would expect to get 0 from my second array.

If it's possible to utilize underscore js for this task, I'm open to using it. I attempted to apply _.contains() but encountered issues. Furthermore, these arrays are being used in a knockout js context.

Answer №1

Here is an alternative method for completing this task:

var    list1 = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]],
       list2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]],["S",["Sally","Sam","Sammy Davis"]]],
getStatus = (list,n) => list.find(item => item[1].indexOf(n) !== -1)[0],
 getIndex = (list,n) => list.findIndex(item => item[1].indexOf(n) !== -1);

console.log(getStatus(list1,"Mary"));
console.log(getIndex(list2,"Sammy Davis"));

Answer №2

let group1 = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]];

let group2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];

group1.forEach(function(item,index,array){
  if(item[1].indexOf("Mary") > -1){
    console.log(item[0]);
  }
});

group2.forEach(function(item,index,array){
  if(item[1].indexOf("Josh") > -1){
    console.log(item[0]);
  }
});

Answer №3

Initially utilizing filter() followed by findIndex()

var students = [["attendance",["John","Josh","Jay"]],["absence",["May","Mary","Mary Jane"]]];
var result1 = students.filter(x => x[1].indexOf("Mary") !== -1)[0][0];
console.log(result1); // absence
var students2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];
var result2 = students.findIndex(x => x[1].indexOf("Josh") !== -1);
console.log(result2); // 0

Answer №4

If you're dealing with a moderate-sized data set, one approach is to store two map objects in memory for faster value access. Keep in mind that this method may not be suitable for handling duplicate names.

The advantage of using this technique is that it only requires looping through each array once. On the other hand, if you rely on methods like indexOf, it will necessitate looping through your data every time you need to retrieve a value.

var arr = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]];
var arr2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];

var makeKeyMap = function(arr) {
  return arr.reduce(function(map, data) {
    data[1].forEach(function(key) {
      map[key] = data[0];
    });
    
    return map;
  }, {});
};

var makeIndexMap = function(arr) {
  return arr.reduce(function(map, data, index) {
    data[1].forEach(function(key) {
      map[key] = index;
    });
    
    return map;
  }, {});
};

var arrMap = makeKeyMap(arr);
var arr2Map = makeIndexMap(arr2);

console.log(arrMap["Mary"]);
console.log(arr2Map["Josh"]);


Edit: testing performance

var myTestData = createTestData();
var randomNameToFind = (function() {
  var namesToFind = ["Aileen","Christina","Donna","Judith","Mandy","Sandra","Dawn","Tracey","Mhairi","Victoria","Carolyn","Gayle","Maria","Valerie"];
  
  return function() {
    return namesToFind[Math.floor(Math.random() * namesToFind.length)];
  }
}());

console.log("Finding the number index for a random name out of 800 names, 10000 times:");

console.time("using index of approach");

var usingIndexOf = (a,n) => a.findIndex(e => e[1].indexOf(n) !== -1);
var results = [];
for (var i = 0; i < 10000; i += 1) {
  results.push(usingIndexOf(myTestData, randomNameToFind()));
}
console.timeEnd("using index of approach");

console.time("using map approach");

var makeIndexMap = function(arr) {
  return arr.reduce(function(map, data, index) {
    data[1].forEach(function(key) {
      map[key] = index;
    });

    return map;
  }, {});
};
var myMap = makeIndexMap(myTestData);
results = [];
for (var j = 0; j < 10000; j += 1) {
  results.push(myMap[randomNameToFind()]);
}
console.timeEnd("using map approach");
console.log("index map size: " + sizeof(myMap) + " bytes");

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

Utilizing Cytoscape JS in Conjunction with JHipster Angular

I've encountered an issue while trying to integrate the plain JavaScript library, cytoscapejs, into my Angular application created with JHipster. I went ahead and installed the library using npm, then added the JS file to my vendor.ts file. However, w ...

How is it possible that the SetTimeout code continues to run even after calling clearTimeout

I have this code snippet within my react component: //some code var timeout = null; //global variable //some more code useEffect(() => { if(...some condition) { console.log('test1'); timeout = setTimeout(() => { ...

Challenges with synchronizing the scope of global arrays when reading JSON files into objects

I'm attempting to load a JSON file into a global array of objects. The code appears to be functioning correctly, however, I am encountering difficulty extracting the data from the Ajax $.getJSON call and storing it in the global variable. This issue c ...

Updating label values to default in JavaScript/jQuery

I need to utilize jQuery/js for the following tasks: Extract label values from form inputs Insert those labels as input values in the corresponding fields Conceal the labels It's a simple task. Instead of manually entering each label like this: $( ...

EJS is failing to render

I am currently working on a rock, paper, scissors game using Node.js on the backend with an express server, frontend.js on the client-side, and index.ejs and main.css files. My goal is to display the result of the player's decision (win, lose, or draw ...

What is the method for selecting a date in an input field using a different date input field?

Two input fields are required, one for fromDate and the other for toDate (both of type date). The fromDate field has a datepicker attached to it. The toDate field is readonly and its date is dependent on the selected date in the fromDate field, being 6 day ...

Tips on eliminating the 'first', 'previous', 'next', and 'last' buttons in the twbs pagination plugin

I am searching for a straightforward pagination solution that only displays page numbers without control buttons like "first," "previous," "next," and "last." I have looked through the options available in twbs-pagination's github documentation and on ...

What methods can be used to transmit binary information from a Node.js socket.io server to a web browser?

After extensively searching the Socket.IO documentation, I am still unable to locate a straightforward example of how to send binary data between a server and client. Despite their assurances that it is included, I have yet to find a minimal demonstration. ...

Tips for retrieving the posted object in angularJS

My current challenge involves creating an object with a defined name, posting it into a database, and then immediately finding its position and obtaining its id. However, I have noticed that using "get" right after "post" retrieves the data before it' ...

Passing an undefined value to the database via AJAX upon clicking a button

Hi there, I'm currently working on a table where I'm trying to perform an inline edit and update the value in the database by clicking on a button (an image). I've attempted to use an onclick function, but it seems to show "value=undefined&a ...

Why is Devtools displaying an unusual numerical value in the console window?

Below is the code I am currently executing in the console. // Utilizing arrow functions without parameters for enhanced readability setTimeout( () => { console.log('Executed first'); setTimeout( () => { // More nested code cons ...

Order the 2D array based on a particular column value in a descending order

I have an array that looks like this: [ ['value' => 1, 'label' => 'General'], ['value' => 2, 'label' => 'Wholesale Customers'], ['value' => 3, 'label&apos ...

Is it possible to utilize JavaScript for rotating and cropping a collection of images before uploading them to the gallery?

Struggling to implement file reader and croppie for local image editing (zoom / rotate / crop) before uploading. Seemingly stuck due to a potential DOM issue with the modal, unable to troubleshoot! FileReader () issues // // //create elements for image, ...

The Price Filtering feature in the MERN Stack for Products is currently experiencing technical difficulties

Hey there! I am currently working on developing an Ecommerce Application using the MERN Stack with redux. I've encountered a problem while trying to send a price array argument in my fetching function. The error message states: XHR GET http://localhos ...

Error: Unable to interpret the URL provided in /api/posts/1

When working on my next.js 13 app, I encountered an issue while trying to fetch individual blog data from a local MySQL database. In the src/blog/[id]/page.js file, I have the following component: const BlogPost = async ({ params }) => { const data ...

What is the process for transforming fetch() into XML HTTP Requests?

In my code, I originally used fetch(), but for my specific situation, using XMLHttpRequest() would be more suitable. However, I am struggling to convert the code to utilize XMLHttpRequest(). This is the original fetch() code: fetch("file.wasm") ...

What is the best way to create a slideshow that automatically starts upon loading and pauses when hovered over?

I have recently set up a div element for my slideshow. I've included a script to enable navigation using next and previous arrows. However, I am looking to add an automatic slideshow feature that stops on hover. As a beginner, I would appreciate any a ...

What is the method for extracting dynamic JSON keys with a value of true?

Here is the JSON response I received: { "A":{"Option1":true,"Option2":true,"Option3":false} "B":{"OptionX":true,"OptionY":true,"OptionZ":false} } I am attempting to extra ...

Oops! There seems to be a mistake - the provider setPageProvider is not recognized

Struggling to implement pagination on my page using the AngularJS framework. Encountering the error Error: [$injector:unpr] Unknown provider: setPageProvider <- setPage. Despite rearranging the code, the issue persists. Attempted following a tutorial fr ...

Creating chainable calculations with the SafeMath class

I'm struggling to find the right keywords for my online search regarding this matter. Recently, I developed a class containing safe math functions. Each function requires 2 arguments and returns the result after undergoing an assertion process. For ...