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

Master the art of filtering rows in an HTML table based on a select option when the mouse is clicked

I am trying to create a table that displays only the rows selected in a dropdown menu. Here is an example: If "All" is selected, the table should display all rows. If "2017" is selected, the table should display only the rows that have "2017" in the sec ...

What is the method for generating a popover in HTML when a user hovers over a button?

In this scenario, I have implemented two status buttons with different colors. The green button corresponds to "RUNNING" and the red button indicates "TERMINATED", which are fetched from JASON data. Upon hovering over the green status button, the text "RU ...

Assigning nested JSON values using Jquery

My JSON data structure is as follows: { "Market": 0, "Marketer": null, "Notes": null, "SalesChannel": null, "ServiceLocations": [ { "ExtensionData": null, "AdminFee": 0, "CommodityType": 0, ...

What is the process of transforming a string into an angular binding?

I have a variable called message that contains the text "you are moving to {{output.number}}". I attempted to insert this into a div element using $("#message").html(message); However, it just displayed the entire string without replacing {{output.number ...

Efficiently Passing Data Between jQuery Dialog Boxes

English is not my strong suit, so please bear with me. I am currently working on a project using Jquery Dialog and I need to display multiple dialogs one after the other (dialog1 opens dialog2 which opens dialog3...) The issue I'm facing is that when ...

Sharing data from parent to child components in Vue.js: A guide to passing references

I need some help with this code snippet HTML Code: <div class="col-xs-4"> <h3 class="text-center">Incomplete task</h3> <div class="well" style="max-height: 300px;overflow: auto;"> <ul id="check-list-box" ...

What could be the reason for the lack of error handling in the asynchronous function?

const promiseAllAsyncAwait = async function() { if (!arguments.length) { return null; } let args = arguments; if (args.length === 1 && Array.isArray(args[0])) { args = args[0]; } const total = args.length; const result = []; for (le ...

Can you explain the execution process of this Http.post method and provide details about the code path it follows

As I delve into the world of web development, one aspect that has me stumped is the functionality of the Http.post section within a project I stumbled upon on GitHub. Specifically, this pertains to an ExpressJS with Typescript repository I came across. So, ...

Is there a way to verify file types using Vuelidate?

Is there a way to validate file types like png, jpg, and jpeg using Vue.js's Vuelidate library? ...

Guide to defining the encoding of an XML file with JavaScript

Hi there, I am currently facing an issue with encoding while creating a document using JavaScript. The problem is that the document rejects all non-ascii characters. For example, when passing the string "verificación", it gets replaced by "". Any suggesti ...

Cloned bootstrap nav tabs are controlled just like the original version

I have a unique scenario where I need to generate a series of "cards" with tabs on top (each card having tabs). To accomplish this, my plan was to use a template element that I can clone and then populate. Everything seems to work fine, except for the tabs ...

Differences between visibility property manipulation in HTML and JS

One issue I am facing is that when I add a hidden property to a button in the HTML, it remains invisible. <button id="proceed_to_next_question" hidden> Next Question </button> However, if I remove the hidden property and include the following ...

Error message received from Express middleware: "Unable to modify headers after they have been sent."

I have created middleware for my Node Express app to perform the following tasks: Checking all incoming requests to determine if they are from a bot Allowing requests for raw resources to proceed Serving an HTML snapshot if the request is from a bot How ...

When using React.js, clicking on an answer option will change the color of all options, not just the one that was clicked

I'm currently working on my quiz page where all answer options change color when clicked. However, I only want the selected answer option to be colored based on its correctness. The data is being retrieved from a data.json array. export default functi ...

Methods for adding a line to an array

I am currently working on a loop where I need to populate my array called photos: $scope.photos = []; var str = data.data.Photos; var res = str.split('|'); angular.forEach(res, function (item) { ...

I do not prefer output as my optimal choice

My preference is to create drill down buttons rather than focusing on output. Currently, the output appears as: The content of index.html is as follows: <html>  <head> <script type="text/javascript" src="http://ajax.googleapis.com/ ...

Error handling in angularJS can be quite challenging at times,

Currently, I am experimenting with AngularJS to develop an application, and I have encountered a challenge related to the $scope context. This is the main file of my app: var app = angular.module('app', [ 'matchCtrl', &apos ...

Unleash the power of jQuery by incorporating the Ajax functionality with a hover option to enhance user interactivity. Utilize the .ajax

On my website, I have a calendar displayed with dates like "11/29/2014" stored in an attribute called "data-date". The goal is to check the server for a log file corresponding to that date and change the CSS of the div on mouse hover. Here is the current ...

Guide for redirecting puppeteers' attention to a new pop-up interface

Currently, I am utilizing Puppeteer to carry out a test on a website. Upon clicking a button, a new popup browser window emerges displaying a report. Inside this new window lies data that I wish to extract. Is there a method for Puppeteer to switch its foc ...

JS: Issue with iterating over objects

Within my JavaScript code, there exists an object named box_object with the following structure: ({ id:"3", text:"this is a box object", connection_parent:["1", "2"], connection_child:["5", "6"], connectiondata_child:{ 0:{id:"5", ...