Steps for organizing a particular key in a map

I need assistance sorting my map based on the "time" value, but so far, I haven't been successful in finding a solution after searching online extensively.

If anyone has any insights or recommendations, please share them with me.

This is how my Map appears:

this.map.set(userData.data()['uid'], { data: userData.data(), lastChat: {message: messages[0].msg, time: messages[0].time}});

uid: {
      data: sampleData,
      lastChat: {
                 message: "A sample text"
                 time: 1640063014931
      }
}

Answer №1

In order to sort a Map, you need to create a new Map with the items added in sorted order. For more information on sorting a Map, you can refer to this thread about sorting an ES6 map object.

To generate a sorted Map:

  1. Convert the Map entries into an array, for example: [...map]. Each entry will be represented as an array with [0] as the key and [1] as the value.
  2. Sort the array based on a specific property of the values, e.g.
    .sort((a, b) => a[1].lastChat.time - b[1].lastChat.time)
    .
  3. Create a new Map using the sorted result.

Below is an example using the time property mentioned in the original question:

const map = new Map();
map.set('0001', {lastChat: {message: 'test', time: 1640063014931}});
map.set('0002', {lastChat: {message: 'test', time: 1640063014930}});

const sortedMap = new Map([...map].sort((a, b) => a[1].lastChat.time - b[1].lastChat.time));

console.log(sortedMap.entries())
// Output: MapIterator {'0002' => {...}, '0001' => {...}}

If there's a possibility of null values in lastChat, additional logic needs to be implemented within the sorting function.

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

Choose from the options provided to display the table on the screen

One of the challenges I am facing involves a table with two columns and a select option dropdown box. Each row in the table is associated with a color - green indicates good, red indicates bad, and so on. My goal is to have all values displayed when the pa ...

Parsing the CSV file contents according to the specified columns

Currently, I'm involved in a project using AngularJS where I need to extract data from a CSV file column by column using JavaScript. So far, I've successfully retrieved the CSV data and displayed it in the console. While I've managed to sepa ...

Unable to import local npm package due to an error

We are in the process of migrating multiple websites, each with its own project, to Vue.js. As we transfer files over and bundle them using Webpack, we have encountered a need to consolidate similar components and core JavaScript files into a shared librar ...

Differences Between DOM and Refs in React

When it comes to React, what distinguishes the use of DOM from Refs? While it is possible to utilize typical JavaScript DOM node selectors in React for targeting specific elements, refs also offer a way to achieve the same functionality. What are the adv ...

Executing a function by clicking on an element with the `ng-click` directive within a Bootstrap modal

I'm working on an app that allows users to submit posts for review. When a user clicks the add post button, I have a Bootstrap modal pop up to confirm their choice. Within this modal, there is a "confirm" button that should trigger a function. Strang ...

Working with jQuery, CSS, and functions to modify the current tag's class

Let's keep it brief and straightforward: Here is my HTML <div id="headerVideoControls" class="overlayElement"> <div id="videoMuteUnmute" onclick="muteUnmuteVideo('headerVideo')">mute button</div> </div> Edited ...

I'm having trouble with my Typescript file in Vscode - every time I try to edit the css code, all the text turns red. Can someone

Check out this visual representation: [1]: https://i.stack.imgur.com/9yXUJ.png Followed by the corresponding code snippet. export const GlobalStyle = createGlobalStyle` html { height: 100%; } body { background-image: url(${BGImage}); ba ...

Database storage of image tags on websites, similar to functionality found on social media platforms such as Facebook

Looking for an image tagging solution for websites that can save tag data directly to a database instead of a local file? I've checked out , but it doesn't support database integration in the current version. Ideally, I need a solution that is co ...

How to surround values and keys with double quotes using regular expressions in JavaScript

I am in need of a valid JSON format to request ES. I currently have a string that looks like this: { time: { from:now-60d, mode:quick, to:now } } However, when I attempt to use JSON.parse, I encounter an error because my ...

AngularJS - Unordered List does not show data

I'm currently delving into angularJS and I've set up a simple example with 2 Views and Controller. The main page defines the controller and route, handling the display of views. The View page is supposed to showcase a text field, unordered list, ...

What is the approach to initiating a jquery function once HTML content is dynamically added through an AJAX call?

<div id="timeline"> <ul class="grow" id="grown"><li>One</li><li>Two</li><li>Three</li><li>Four</li><li>Five</li><li>Six</li><li>Seven</li><li>Eight< ...

JavaScript's innerHTML property is failing to update

Hello there, I am currently attempting to update the innerHTML content of the script below: <div id="global-alert-queue" class="layout-wrapper"> <div class="alert success animate-in" role="alert"> Your submission was successful. <button i ...

Issue with event binding on datepicker that is dynamically added is not functional

I have integrated the Kendo datepicker into my project, and I am facing an issue with duplicated div elements containing datepickers. The problem is that the datepicker events only fire once on the first duplicated div and then stop working altogether. I ...

"How to prevent users from using the back button on Google Chrome and Edge browsers

window.history.pushState(null, null, location.href); window.addEventListener('popstate', () => { history.go(1); alert('The use of back button is restricted.'); }); An issue has been identified where the code snippet above d ...

Tips for extracting a value from a mongodb aggregate operation

I am attempting to retrieve a value from a MongoDB aggregate in order to display it on an EJS page using the totalAmount variable. The result I am currently receiving is [{"totalAmount":42}] and my goal is to extract only the number, in this case, 42. My ...

Sending Ajax requests to web services hosted on a dual-node NLB

I am currently managing a two-node NLB configuration where multiple web services need to be accessed from the client-side using ajax POST requests. When visiting the page at: http://clusternode1/ everything works smoothly. Similarly, when accessing it f ...

The dropdown height feature is experiencing issues in the Chrome browser

3 radio buttons and a single select box are displayed on the page. When clicking on the first radio button, the select box should show contents related to the first radio button. However, when selecting the second or third radio buttons, the select box hei ...

Converting PPT files to PDF or PNG using Node.js

Are there any options available for converting ppt files to pdf or png without relying on specific operating system dependencies? I need to convert a ppt file to png, but all the current packages I have tried require tools like LibreOffice or ImageMagick ...

Monitor files in different directories with the help of pm2

Can pm2 detect changes in directories outside of the current one? For example, if I have an index.js file in /home/sprguillen/workspace/node that needs to be run by pm2, but my configuration file is located outside in /home/sprguillen/workspace/config. I ...

Utilizing the array result obtained from the fetch function

Seeking assistance with a coding issue. I am puzzled as to why I am unable to utilize the data returned from an API call outside of its function, even though there are no errors occurring. The fetchUser function successfully retrieves the data from the API ...