What is the best way to add new key value pairs to the dictionary?

I am attempting to distinguish between single clicks (assigned value 0) and double clicks (assigned value 1), while also keeping a log of the click and its position in a map. However, I have noticed that the keys are automatically sorted in ascending order, even though I did not intentionally sort them. Is there a way to incorporate the position key along with the corresponding value of 1 or 0 at the end while ensuring that all clicks are properly recorded? I even attempted converting the key to a string using String(i).

If you'd like to see the entire code for the project I'm currently working on, it can be found here: Codesandbox

var lastClicked;
var map = {};

var grid = clickableGrid(20, 30, function(el, row, col, i, isDoubleClick) {

  if (!isDoubleClick && !el.className) {
    el.className = "clicked";
    map[String(i)] = 0;
  } else if (isDoubleClick && !el.className) {
    el.className = "niclicked";
    map[String(i)] = 1;
  }
  console.log(map);
});

document.body.appendChild(grid);

Answer №1

It's important to note that the order in which keys are visited in plain objects during iteration is not guaranteed to be based on insertion-order. Positive integers within the 32-bit range are visited in numerical order.

For maintaining insertion order, arrays are a good option as they follow the sequence of elements added using push. However, unlike dictionaries, they do not support key-based entry retrieval.

If you require both dictionary behavior and insertion order preservation, utilizing a Map can be beneficial:

var lastClicked;
var map = new Map; // <---

var grid = clickableGrid(20, 30, function(el, row, col, i, isDoubleClick) {

  if (!isDoubleClick && !el.className) {
    el.className = "clicked";
    map.set(i, 0);
  } else if (isDoubleClick && !el.className) {
    el.className = "niclicked";
    map.set(i, 1);
  }
  map.forEach((value, key) => console.log(key, value)); //<-- insertion order!
});

document.body.appendChild(grid);

You can use: map.get(key) to efficiently retrieve the 0/1 value associated with a specific key, similar to a plain object.

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

Authenticating with passportjs using a Google Apps email address for verification

I am currently experimenting with using Passport.js along with a Google Apps email ID. I have successfully been able to authenticate using a gmail.com email ID, however, I am facing challenges when attempting to authenticate if the email ID is associated w ...

What could be causing external stylesheet styles to take precedence over internal and inline styles?

Currently, I am working on a website that utilizes a global stylesheet which applies styles to specific element types. Personally, I find this approach inefficient. As I develop ASP.NET user controls for different pages, I consistently encounter issues whe ...

Adjust the height of a div element and enable scrolling to fit the

There are numerous inquiries regarding this particular issue. I have exhausted nearly all possible solutions I could find, yet none of them delivered the desired outcome. This is the structure of my page: <div> <header id="status"> / ...

Unable to utilize the forEach() function on an array-like object

While I generally know how to use forEach, I recently encountered a situation that left me puzzled. Even after searching online, I couldn't find any new information that could help. I recently started delving into TypeScript due to my work with Angul ...

Having difficulties integrating a login solution due to an error saying "eslint Promise executor functions should not be async no-async-promise-executor"

I'm currently working on integrating a login solution into my Vue app using the JWT Authentication plugin. While I have a test solution that is functional, I'm facing an issue in my main branch where the eslint version seems to be causing an err ...

Basic node.js server that responds with HTML and CSS

I have successfully created a basic http server to send an HTML file as a response. However, I'm struggling with how to also send a CSS file so that the client can view the HTML page styled with CSS in their browser. Here is my current code: var htt ...

Simple steps to validate an ajax response with a specific string

I'm encountering a problem with a simple ajax call that involves checking the returned text against a string: // in my php file echo 'mystring'; // in my javascript if((request.readyState == 4) && (request.status == 200)){ if(req ...

How can I assign a prop to a component within the root layout in Next.js version 13, especially when the root layout is required to be a server-side component at all times?

I need assistance with a project I'm working on. My goal is to create a SongPlayer component in Next.js version 13 that plays music and is positioned at the bottom of the window, similar to Spotify's player. However, my SongPlayer component requi ...

How to make browsers refresh cached images

.button { background: url(../Images/button.png); } Issue: To improve performance, static content on the website is cached with expiration headers. However, when an image changes, users must manually refresh their browser cache (Ctrl+F5 in IE). ...

Text centered over an animated underline using CSS

Seeking help with my bootstrap 4 nav menu. I have implemented a CSS animation that creates an outward underline effect for the nav-link items. However, I am struggling to center the text above the line. Any suggestions on how to achieve this? I attempted ...

Interacting with an element within a jQuery dialog box created through a function click

I'm encountering an unusual issue with jQuery and Javascript across all browsers (IE, FF, Chrome). On my (asp.net) webpage, I have the following structure: A header with numerous dynamically generated buttons at PreRender A hidden div containing but ...

Every outcome was displayed within a table format rather than as individual rows

I'm having trouble with my PHP code for search. The result is not displaying in a single table with rows, as expected. I attempted to modify the PHP by changing `'<td>','<div>' . $row['$accountcode']. '&l ...

the conditional operator used without assigning the result to a variable

Exploring conditional operators on html canvas, I am seeking a streamlined approach to dynamically change stroke color based on conditions. Online examples have not provided a satisfactory solution in a single line of code. Currently, without using a cond ...

Move the navigation bullets of the Nivo Slider to the bottom instead of below the slider

Currently working on a website and have incorporated Nivo Slider to develop a jQuery slider. Encountering an issue with the bullets that indicate which slide the user is currently viewing. I'd like these bullets to be displayed on the images within t ...

Guide to configuring Winston logging with Sequelize correctly

Currently, I am setting up winston with Sequelize and have the code snippet below: const logger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ new winston.transports.File({ filename: path. ...

Switch positions of two objects in JavaScript

Check out the code snippet below: MyObject.prototype.doIt = function() { let a = this.obj1; let b = this.obj2; } I need to find a way to switch the values of this.obj1 and this.obj2, making obj1 take on the value of obj2 and vice versa. Pleas ...

What is the best way to vertically center an amp-img element?

I'm attempting to vertically center an <amp-img> within a div. <div class="outer" style="height: 100vh"> <amp-img class="inner" layout="responsive"></amp-img> </div> I have tried various methods so far, but none seem ...

The concepts of width and min-width in CSS allow for controlling

I have a table with the following styles applied: width: auto; min-width: 98.5%; When viewing in Chrome, the table inside a div appears to only be about 50% of the width of the containing div. However, in IE9, the table occupies the full width. Checking ...

Sending a message through Discord.JS to a designated channel

Recently diving into Discord.JS, I am struggling to understand how to make my bot send a message to the General Chat when a new user joins. Many examples I've come across suggest using the following code: const channel = client.channels.cache.find(ch ...

Using DOMParser() eliminates whitespace

Basic code example: const parser = new DOMParser(); const foo = parser.parseFromString(<p> Foo</p>, 'text/html'); console.log(foo); This results in https://i.sstatic.net/8E2br.png Why have all the leading empty spaces before " ...