Arranging a map by its keys results in a sorted Map object with the initial key located at the end of

I have a function that creates a Map object from two arrays and then attempts to sort the map by key. Despite following the sort method as outlined in Mozilla Docs, the sorting is not working as expected; it places the first key at the last index when using the mapSort object.

const sortMapByKey = () => {
  const keyArray = [4, 6, 16, 18, 2]
  const valueArray = [103, 123, 4444, 99, 2000]

  const buildMap = (keys, values) => {
      const map = new Map();
      for(let i = 0; i < keys.length; i++){
        map.set(keys[i], values[i]);
      };
      const mapSort = new Map([...map.entries()].sort(function(a, b) {
        return a - b;
      }));
      return mapSort
    };  
    
    return buildMap(keyArray, valueArray)
}

The current output:

Map { 4 => '103', 6 => '123', 16 => '4444', 18 => '99', 2 => '2000' }

The desired output:

Map {  2 => '2000', 4 => '103', 6 => '123', 16 => '4444', 18 => '99' }

I'm puzzled about what might be going wrong with my sort implementation. Any insights?

Answer №1

In this scenario, the entries are represented as key-value pairs, for example: [1, 103]. The code snippet return a - b attempts to subtract two arrays containing such entries, which is not meaningful. Instead, it is necessary to extract the key from each entry pair before performing any operations.

const mapSort = new Map([...map.entries()].sort(function(entryA, entryB) {
  return entryA[0] - entryB[0];
}));

const keyArray = [4, 6, 16, 18, 2]
const valueArray = [103, 123, 4444, 2000]

const buildMap = (keys, values) => {
  const map = new Map();
  let objectArray = []
  for (let i = 0; i < keys.length; i++) {
    map.set(keys[i], values[i]);
  };
  const mapSort = new Map([...map.entries()].sort(function(entryA, entryB) {
    return entryA[0] - entryB[0];
  }));
  return mapSort
};

console.log(buildMap(keyArray, valueArray));

Alternatively, you can utilize destructuring like so:

const mapSort = new Map(
  [...map.entries()]
    .sort(([a], [b]) => a - b)
);

const keyArray = [4, 6, 16, 18, 2]
const valueArray = [103, 123, 4444, 2000]

const buildMap = (keys, values) => {
  const map = new Map();
  let objectArray = []
  for (let i = 0; i < keys.length; i++) {
    map.set(keys[i], values[i]);
  };
  const mapSort = new Map(
    [...map.entries()]
      .sort(([a], [b]) => a - b)
  );
  return mapSort
};

console.log(buildMap(keyArray, valueArray));

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

How to update a boolean value in a JSON object using AngularJS?

Trying to modify a boolean value when a user clicks on a JSON-populated table row. Here's an example of the setup... $scope.prices = { "Prices": [ { "Code": "edl", "Selected": false }, { "Code": "ead", "Sel ...

Angular is attempting to call the $http method and trigger the success callback even

I have implemented a function in a service: function retrieveData(link) { return $http.get(link).then(function (res) { return res.info; }); } If the request is successful, everything works smoothly - I receive a promise as expected. Howe ...

Ways to organize the elements within an inner array while also preserving distinct sorting for external documents

Currently, I am dealing with a set of documents, each containing an embedded array. What I need is to sort the elements within each array while keeping the order of the main documents intact. For example, let's refer to data provided in this similar ...

Set up a targeted version of the winston software package for installation

Can I download a specific version of winston through npm by using the command: npm install winston=2.2.0 The reason I am asking is because I am encountering an issue with my existing code written in version 2.2.0 when I download the latest version. The ...

Unsure why my React component isn't triggering a re-render?

I encountered an issue when trying to update my component based on a state change. When I update the state outside of an HTTP call, the component updates correctly. However, when I try to do the same inside an HTTP get call, the state is updated but the ...

Utilizing Django models to populate Google Charts with data

I am currently working on showcasing charts that display the most popular items in our store. To achieve this, I need to extract data from the database and incorporate it into the HTML. Unfortunately, the charts are not loading as expected. When testing wi ...

Setting up Django model form using jQuery and JavaScript

In my project, I am working with three different models: class Instances(models.Model): name_of_instances = models.CharField(max_length=255) url_of_instances=models.URLField(max_length=255,default='') def __str__(sel ...

Animating HTML 5 canvas with keydown events

As a newcomer to programming, I've been experimenting with HTML 5 and canvas. My goal is to make a simple rectangle move when a key is pressed, but I'm facing difficulties in achieving this. I tried following the instructions provided in this gui ...

Capture data from clipboard as it is being pasted into Handsontable

Issue Description and Troubleshooting: In a nutshell, I am seeking a method to manage data copied from the clipboard to a handsontable. I came across a suggestion on how to fetch this information using jQuery in a stackoverflow post: $("#haras_excel_li ...

Organizing an array of objects within MUI cards based on social media platforms

I'm currently developing an application that showcases athlete data in a grid layout using MUI Grid. The colored borders on the left side of each card are determined by the corresponding social network associated with that athlete. https://i.sstatic. ...

Monochrome Effect Triggered by Cursor Hover

I'm attempting to use Javascript with HTML5 canvas to convert an image to greyscale, but I seem to be missing something in my code. Can anyone spot the error? I feel like I'm very close! function grayscaleConversion(str) { // Access the Canv ...

Discovering the Keys of a Multidimensional Array in JSON with AngularJS

I'm attempting to create a form using a JSON array. I want to display the keys in the HTML. Check out this example array: { "Fred": { "description": "A dude" }, "Tomas": { "description": "Another Dude", "Work": { "Current" ...

What are the steps to implement localStorage in Vuejs3?

I'm feeling a bit lost when it comes to localStorage and its usage. I have a component called Statistic.vue which displays a modal at the end. Statistic.vue <template> <p class='modal'>{{numberOfGames}}</p> </template& ...

Analyzing two arrays in C#

Just getting started with C# and running into an issue while comparing two arrays. Both arrays have the same values, so they should be equal, but the result is always false. Not quite sure what's causing this. char[] arOne = { 'a', 'b ...

I am unable to update an array within my component using useEffect

Encountered two problems, firstly while attempting to pass an array of objects from a parent component to a child component, facing difficulties as shown below: function DropdownSome ({options, placeholder, someNum}) { const [value, setValue] = useState ...

Ways to retrieve the index of a randomly selected JSON file from a list

I'm currently working on a script for a book selection randomizer and I'm trying to figure out how to also display the index number of the chosen book from a JSON list. Here is my function for displaying all the data: def view_data(): with open ...

Tips for Deploying Your NuxtJS Project on a Shared Hosting Service

After creating my NuxtJS project locally, I am now facing the challenge of deploying it to a shared hosting provider like Host Gator. Since I intend to utilize the server side rendering feature of NuxtJS, I know I need to execute the following command: n ...

Can you explain the distinction between using `new ObjectId()`, `new ObjectId`, and `ObjectId()` in

Consider this initial definition in a file: const ObjectId = mongoose.Types.ObjectId; Which method should you choose and why? // 1 new ObjectId; // 2 new ObjectId(); // 3 ObjectId(); The official documentation recommends using new ObjectId. Person ...

Find the flowplayer when the page loads

Is there a way to make a flowplayer seek at the page load without it resetting? I've tried this: $(document).ready(function() { $f(0).seek(5); }); also tried: $(document).ready(function() { while(!$f(0).isLoaded()) { $f(0).seek(5); } }); ...

Utilize the Magento extension to seamlessly integrate JavaScript code into the head section of your website

I am attempting to incorporate JavaScript code into all or some pages of my website using an extension. I require a dynamic version (hosted in a .phtml file) of the following script: <default> <reference name="head"> & ...