Arrange the keys of a map in ascending order, prioritizing special characters and their precedence

JavaScript ES6 Map Example:

const map = new Map();
map.set('first', ['1', '2']);
map.set('second', ['abc', 'def']);
map.set('_third', []);
map.set(')(*', []);
map.set('he__e', []);

console.log(map);

One important thing to note about a Map object is that it iterates its elements in insertion order.

I decided to sort the map in ascending order as shown below:

var mapAsc = new Map([...map.entries()].sort());
console.log(mapAsc)

However, the output seems unexpected:

0: {")(*" => Array(0)}
1: {"_third" => Array(0)}
2: {"first" => Array(2)}
3: {"he__e" => Array(0)}
4: {"second" => Array(2)}

Why does the index '3' contain special characters? I would like the output to be as follows:

0: {")(*" => Array(0)}
1: {"_third" => Array(0)}
2: {"he__e" => Array(0)}
3: {"first" => Array(2)}
4: {"second" => Array(2)}

Answer №1

let uniqueTags = new Map();

Below is an example data from my object that I'd like to share:

 uniqueTags = {
          web: {
              tagName: "web",
              contentID: Array(7),
              contentTypes: Array(2),
              tagURL: Array(1),
              occurrences: 7
            }
         }

//

let sortedUniqueTags = new Map();
    for (let tagValue in uniqueTags) {
        for (let i = 0; i < tagValue.length; i++) {
          if (/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi.test(tagValue.charAt(i))) {
                  sortedUniqueTags[tagValue] = uniqueTags[tagValue];
           }
         }
     }// 0(n2) order of n2

After moving all the keys with special characters into another Map object, I proceed to copy over the remaining keys using the loop below.

for (let tagValue in uniqueTags) {
        if (uniqueTags[tagValue] !== sortedUniqueTags[tagValue]) {
            sortedUniqueTags[tagValue] = uniqueTags[tagValue];
        }
    }

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 steps do I need to take to incorporate dialog-polyfill into my React application?

Incorporating Firebase and FirebaseUI in my React application for phone number registration has been successful on Google Chrome desktop. However, when testing it on different browsers, such as through , I encountered an issue with the country code selecto ...

Stop users from submitting empty forms

I'm facing an issue with my form where I want to prevent it from being submitted if the fields are blank and also highlight those blank fields. The code I currently have works when trying to submit with blank fields, but for some reason, it doesn&apos ...

A step-by-step guide on how to repeatedly reload a nextJS page using recursion and display an error page once the

I've been experimenting with a recursive page reload function that looks like this: export const refreshPage = (count)=>{ if (count <= 0){ // window.location.reload(); console.log("blue"); return }else { console.log(& ...

Tips for ensuring all data is properly set before saving in mongoose

Struggling to update undefined or defined values in Mongoose due to the need to await their assignment. It seems like the code is not saving the data because USER.save() is executed before the values are set. How can I ensure that the data is updated/set ...

What strategies can I use to refactor this controller in Angular 1.5 to make it more concise and efficient

I am encountering an issue with a component I have that contains a button. Whenever the button is clicked, it triggers one of two backend services depending on where the component is located. To achieve this, I am currently passing a flag to the component ...

"Exploring the differences between request.body, request.params, and request.query

I am working with a client-side JS file that includes: agent = require('superagent'); request = agent.get(url); Afterwards, the code looks something like this: request.get(url) //or request.post(url) request.end( function( err, results ) { ...

Converting URL for AJAX POST information

While trying to encode a URL using encodeURIComponent, I encountered a 500 SERVER ERROR on certain URLs. It appears that the issue lies in the encoding process, as removing the data resolves the error entirely. What is the correct way to encode the URL to ...

Having difficulty encapsulating three.js rendered particles within a single div

I'm facing an issue where the particles generated by my three.js project are not contained within a specific div or html element as intended. Instead of staying within the designated boundaries, the particles are spreading across the entire DOM witho ...

Using AJAX in a loop presents a challenge: What is the best way to initiate an ajax request for every item in an array?

Hey there! I'm a new member of the StackOverflow community and I could really use some assistance. My current challenge involves performing an inverse geocode to retrieve addresses from coordinates. I have a functional URL that works with ajax, but I ...

A step-by-step guide on utilizing img src to navigate and upload images

I would like to hide the input type='file' element with id "imgInp" that accepts image files from users. Instead, I want them to use an img tag to select images when they click on a specific img tag. How can this be achieved using jQuery? Here i ...

Encountering an unexplained JSON error while working with JavaScript

I'm trying to retrieve data from a JSON API server using JavaScript AJAX and display it in an HTML table. However, I keep encountering an undefined error with the data displaying like this: Name id undefined undefined This is my code snippe ...

Concealed Selenium File Upload through Drag and Drop User Interface

Struggling to insert an image into the specified input using selenium web-driver. <input type="file" multiple="multiple" class="dz-hidden-input" accept="image/gif,image/jpg,image/jpeg,image/png,application/zip" style="visibility: hidden; position: abso ...

Fade out a component in Material UI/React by setting a timeout in the parent's useEffect hook for when it unmounts

Incorporating a fade out transition into my child component, <Welcome />, using Material UI's Fade component is my current goal. This transition should be triggered by two specific conditions: The timeout set in the useEffect function expires. ...

What could be causing WidgEditor, the JavaScript text editor, to fail to submit any values?

After clicking submit and attempting to retrieve text from the textarea, I am encountering a problem where the text appears blank. The reason for this issue eludes me. function textSubmit() { var text = $("#noise").val(); console.log(text); consol ...

Error caused by MongoClient TypeError

As a newcomer to NodeJS and someone exploring Dependency Injection for the first time, I encountered an error that led me to seek help. Before asking my question, I reviewed some similar threads on Stack Overflow: [1][2] Upon running my main code, I recei ...

What is the equivalent of defining conditional string types in Typescript similar to flow?

type UpsertMode = | 'add' | 'update' | 'delete'; interface IUpsertMembers { mode: UpsertMode; } const MagicButton = ({ mode: UpsertMode }) => { return ( <button>{UpsertMode}</button> ); } const Upse ...

What is the best way to incorporate Express following an asynchronous function?

After setting up my Firebase and initializing it, I managed to retrieve data from it. However, I encountered an issue when trying to use express.get() and json the data into the server. I'm unsure of what the problem could be. let initializeApp = requ ...

JavaScript problem with setting values in 2D array

I am attempting to assign values to a 2d array at particular indices. During each iteration, all sub-arrays at the j index are being assigned the same variable (number). inputTensor dimensions: 140x7 - 140 arrays of size 7 inputMinArray dimensions: 1x7 - ...

Exploring AngularJS $compile and the concept of scoping within JavaScript windows

I've encountered a scoping issue with the use of this inside an angular-ui bootstrap modal. The code below functions perfectly outside of a modal, but encounters problems when run within one: var GlobalVariable = GlobalVariable || {}; (fun ...

Is there a way for me to identify when I am "traveling" along the same path?

I want to create a toggle effect where a view is hidden if the user tries to revisit it. This can be useful for showing/hiding modal boxes. Here's the code I attempted: /* Root Instance */ const app = new Vue({ router, watch: { '$route&a ...