What is the best way to retrieve a specific key from a JavaScript Map containing an array?

I am currently iterating through a two-dimensional array to populate a map. The map is using the [i,j] indices as keys and the corresponding arr[i][j] values as values:

const arrMap = new Map()

for(let i = 0; i < arr.length; i++){
        for(let j = 0; j < arr[i].length; j++){
            arrMap.set([i,j],arr[i][j]);
        }
    }

After logging the Map, it appears to have been set correctly with pairs like: [0,0] => "A". However, when I try to retrieve the value using: arrMap.get([0,0]), it returns undefined. How can I access the value "A" from arrMap?

An example array I would iterate through is:

[ ["A","B","B"],["A","A","A"] ]

There is a similar question discussed here- Array as a javascript map's key?, but the answer provided did not clarify the issue for me.

Answer №1

Upon careful examination of the response to the previous question, it becomes evident that your attempt to retrieve the array [0,0] is flawed as it is not the same array [0,0] that was originally set. One solution could involve converting the array key into a string. Here's an example:

const arrMap = new Map();
const arr = [
  [1, 2, 3],
  [4, 5, 6]
];

for (let i = 0; i < arr.length; i++) {
  for (let j = 0; j < arr[i].length; j++) {
    arrMap.set(JSON.stringify([i, j]), arr[i][j]);
  }
}
console.log(arrMap.get(JSON.stringify([1, 1]))); // 5

Answer №2

When dealing with objects and their unique references, a wrapper is necessary to effectively store and retrieve values.

This wrapper generates a primitive value (string) independent of object references.

const
    wrapperFunction = array => array.join('|'),
    arrayInput = [["A", "B", "B"], ["A", "A", "A"]],
    arrayMap = new Map();

for (let i = 0; i < arrayInput.length; i++) {
    for (let j = 0; j < arrayInput[i].length; j++) {
        arrayMap.set(wrapperFunction([i, j]), arrayInput[i][j]);
    }
}

console.log(arrayMap.get(wrapperFunction([0, 0]))); // A

Answer №3

transform key into a string data type

arrMap.set([x,y].toString(),arr[x][y]);

you can loop through to retrieve the key and its corresponding value

 for(let [key, value] of arrMap){
     console.log(key)
     console.log(value)
    }

if you need direct access

arrMap.get('2,1')

Answer №4

When working with a key like [0, 0], it's important to remember that it is a reference type. This means that each time you write the same array, you are creating a new reference. This is why when using a Map, which does not have the same reference mechanism, you may encounter the issue of getting undefined. To avoid this, consider using a primitive type as a key instead.

To see all keys within your Map data structure, you can utilize the keys() method and then access the desired key accordingly:

Using a primitive value as a key is recommended because each time a value is accessed by declaring an array, a new reference is created. As a result, the key in your Map object may not match the new reference:

const arrMap = new Map()

let arr = [[1, 2, 3], [4, 5, 6], [7]]

for(let i = 0; i < arr.length; i++){
        for(let j = 0; j < arr[i].length; j++){
            arrMap.set(`${i}, ${j}`,arr[i][j]);
        }
}

for (let key of arrMap.keys()) {
  console.log(`key: `, key);
  console.log(`result: `, arrMap.get(key));
}

let result = arrMap.get('0, 0');
console.log('The value by key of primitive type: ', result);

Answer №5

The key in a Map needs to be the actual key of the array in order to be retrieved correctly. This means if you want to use an array as a key, it must be the same array object that was originally set as the key.

Here's an example to help illustrate:

const map = new Map()
map.set([0, 0], 'A')

const keyZ = [2, 2]
map.set(keyZ, 'Z')

console.log(map.get([0, 0])) // won't find
console.log(map.get(keyZ)) // will output Z

const keyA = [0, 0]
map.set(keyA, 'A')
console.log(map.get(keyA)) // will output A

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

JavaScript Time and Date Formatting

I'm pretty new to programming, especially in Javascript. Can someone help me simplify my code? I'm trying to create a dropdown for months and an input field for the year. Is there a more efficient way to make the month select box? Also, how can ...

What is the best way to check for incorrect or missing values when comparing two Arrays?

Can you help me with comparing two arrays, $original and $duplicate? Here is the content of my original array: print_r($original); Array ( [0] => cat423 [1] => dog456 [2] => horse872 [3] => duck082 ) And this is my duplicate array: pr ...

jQuery element with listener not triggering as expected

I'm facing some confusion while working on this issue. I am attempting to create a dynamic form where users can add descriptions, checkboxes, and number inputs as they please. Currently, I have developed a simple dynamic form using jQuery, which allow ...

Generating Vuetify badges and icons with createElement in the render function: A step-by-step guide

Within my Vue application, I utilize a v-data-table. The column values are generated using a render function within a functional component as illustrated below: render(createElement) { if (this.$props.format) { return this.$props.format(this.ite ...

Developing an npm library with ReactJs: A step-by-step guide

As a newcomer to React, I am eager to create my own npm library in ReactJS. Taking inspiration from my existing React project, the goal is to transform it into a package (or library) that can be easily integrated into other projects. This means allowing ...

The pagination feature for Swiper is experiencing issues across both desktop and mobile platforms

I am having an issue with the pagination display in the text. I would like it to appear below the text as a standalone item for better visibility. Another problem arises when viewing the page on mobile devices - the hamburger menu displays behind the slid ...

Issues with JQuery Ajax rendering in browser (suspected)

I'm encountering an issue on my webpage. I have a div with two hidden fields containing values of 0 and 2, respectively. Upon clicking a button that triggers an AJAX query, the div contents are updated with hidden field values of 1 and 2. However, it ...

AngularJS - Shared service object mistakenly removed in error

When I call the removeQuestion() function for the second time, 2 questions are being deleted instead of one. Any suggestions on what might be causing this issue? Let me know if you require additional code snippets. controller.js crtPromoCtrl.controller(& ...

Encountering issues when attempting to install vue-cli on a new project

After creating an empty project, I attempted to install vue-cli using the command npm install -g @vue/cli. However, during the installation process, I encountered the following errors and warnings from the interpreter: npm WARN read-shrinkwrap This versi ...

multiples of order quantities in WooCommerce

In order to implement a minimum order quantity based on category, I came across this code. However, it seems to apply to all products in the cart. What additional modifications would be needed to specify certain categories? My objective is for customers t ...

Can you save data entered by a user into a text file using JavaScript or a similar technology in HTML, without the need to send it to a server?

Is there a way to create a site where user data is inputted into an input box or form, and then that information is stored in a .txt file on the user's C drive without uploading it to a server first? I've been experimenting with various forms an ...

Regular pattern with Kubernetes cluster endpoint utilizing either IP address or fully qualified domain name

In my Angular/typescript project, I am working on building a regex for a cluster endpoint that includes an IP address or hostname (FQDN) in a URL format. For instance: Example 1 - 10.210.163.246/k8s/clusters/c-m-vftt4j5q Example 2 - fg380g9-32-vip3-ocs.s ...

Automatically hide a label after a certain amount of time following a button click

Currently, I am working with ASP.NET and C#. Within my application, there is a registration form that includes a label to display the status of registration, either success or failure. The content of this label is determined dynamically in the codebehind ...

Illustrating SVG links

I'm working on a basic svg animation project where I want to create a simple shape by animating a line under a menu link. The goal is to have a single line consisting of a total of 7 anchors, with the middle 3 anchors (each offset by 2) moving a few p ...

Is there a way to retrieve the ngModel reference of a child element within a directive's

I am currently utilizing bootstrap-colorpicker along with an angular directive in my project. Within my form, there is a colorpicker that I want to monitor for any changes. However, since the colorpicker jQuery plugin updates the value of the colorpicker, ...

PHP: iterating through an object

Apologies if this question seems obvious, but I've been stuck on it for quite some time and can't figure out the solution. Here is the code snippet I have: $objectPerson = new Person(); $objectPerson->setName($arrayName); $objectPerson->s ...

How can I determine if a URL in react js includes a specific string?

I am working on a project where I need to check if a given URL contains the string youtube using react hooks in React JS. This is what my current code looks like: useEffect(() => { let srcLink = "www.google.com/https://img.youtube.com/vi/h9-qcy3HQn ...

Using jasmine for mocking jQuery's getJSON callback function is a helpful technique in testing your

In my module, there is a load function that utilizes jQuery's getJSON function to fetch data. load(key,callback){ // validate inputs $.getJSON( this.data[key],'',function(d){ switch(key){ // perform actions on the data bas ...

The onClick event handler fails to trigger in React

Original Source: https://gist.github.com/Schachte/a95efbf7be0c4524d1e9ac2d7e12161c An onClick event is attached to a button. It used to work with an old modal but now, with a new modal, it does not trigger. The problematic line seems to be: <button cla ...

A detailed guide on sending Joomla form information to a controller function using Ajax communication

Within my Joomla 3.3 form, I have integrated an ajax script aimed at dynamically updating some form fields. The core of the script looks like this: formdata = new FormData(); jQuery.ajax({ type: "POST", dataType: "json", timeout: 6000, url: "index.php?opt ...