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

Assigning a value to an input field using jQuery

I'm facing an issue while trying to set the value for an input using jQuery. Essentially, when you click on a link, it redirects you to a different page with a form, and I am attempting to set the value of one of the inputs in that form. Unfortunately ...

Execute a database query to search for patterns using Regular Expressions within the

As I embark on a new project, I find myself questioning my approach before diving in too deep and realizing it may not be the most efficient path. Within the realm of a large company where we develop unofficial tools for internal use, I am faced with limi ...

Is there a way to determine if a directory is empty using Node.js?

Quite a while back, I submitted a question related to PHP. Now I'm facing a similar situation with Node.js where the code below appears to be sluggish when used in a loop - is there a way to achieve this using only vanilla JavaScript in pure Node.js w ...

Tips on adjusting the point size in ChartJS

I am looking to minimize the size of the data points on my chart. https://i.sstatic.net/CKtQX.png I have attempted to achieve this by using pointHoverRadius: 1 However, this method does not seem to be effective. Thank you for your assistance, ...

Is it possible to reference the prior value of a computed Angular signal in any way?

Is it possible to dynamically add new values from signal A to the existing values in signal B, similar to how the scan operator works in RxJS? I am looking for something along the lines of signalB = computed((value) => [...value, signalA()]). Any sugg ...

What are the steps for encountering a duplicate property error in TypeScript?

I'm currently working with typescript version 4.9.5 and I am interested in using an enum as keys for an object. Here is an example: enum TestEnum { value1 = 'value1', value2 = 'value2', } const variable: {[key in TestEnum]: nu ...

Reset checkboxes in Material UI data grid

Currently, I am immersed in a React Js project that involves various tabs, each containing a unique data grid table with rows featuring checkboxes. Issue: Whenever I select a row from Table 1 and navigate to Tab 2 before returning to Tab 1, the checkboxes ...

Utilize Jquery to dynamically modify the content on a webpage

I am looking to use Tampermonkey in order to reverse the text on a specific website, like BBC News. I have already started working on a script that can replace certain text, but I am facing difficulty in accessing all the text present on the page efficient ...

Material-UI: The `paperFullWidth` key passed to the classes prop is not supported within the WithStyles(ForwardRef(Dialog)) component

When using Material-UI, please note that the key paperFullWidth provided to the classes prop is not implemented in WithStyles(ForwardRef(Dialog)). You are only able to override one of the following: root. <Dialog classes={{ paperFullWid ...

How to achieve the wrapping functionality in ReactJS that is similar to

Is there a ReactJS equivalent to jQuery's wrap method? I want to wrap menuContents with the following element: <ul className="nav nav-pills nav-stacked"></ul> The contents of menuContents are generated like this: let menuContents = thi ...

What is the maximum number of groupings that can be created from a set of numbers within a

I'm trying to figure out how to handle a specific task, but I'm running into some obstacles. When adding numbers to clusters, a number is considered to belong to a cluster if its distance to at least one existing number in the cluster is within a ...

In React components, encountering "cannot read properties of undefined" error occurs, whereas it functions perfectly fine within the getStaticProps

I am currently in the process of setting up a blog using Node.js, React, and graphql. Despite being new to these technologies, including Java and Typescript, I am seeking assistance from anyone who may be able to help. My current roadblock involves display ...

JavaScript issue causing input fields to malfunction and clear text boxes

I apologize for the simplicity of this question, but I am struggling with an issue and seeking help. Here's the problem: my calculate() method is not clearing text input as expected when testing my page. Below is the HTML markup and script: <!DOC ...

Utilizing jQuery to toggle a dropdown box based on multiple checkbox selections

After conducting a search, I came across a helpful resource on Stack Overflow titled Enable/Disable a dropdownbox in jquery which guided me in the right direction. Being new to jQuery, I found it useful to adapt code snippets to suit my needs. Now, my que ...

The TypeScript compiler is indicating that the Observable HttpEvent cannot be assigned to the type Observable

Utilizing REST API in my angular application requires me to create a service class in typescript. The goal is to dynamically switch between different url endpoints and pass specific headers based on the selected environment. For instance: if the environmen ...

What do you prefer: defining properties with the JSON object or with objectName.property in JavaScript

Can you tell me which approach is considered the best practice? Is it better to use the "this" statement in the following way: var obj = { x: 20, y: 10, width: this.x, height: this.y, render: function () { // renders object on canvas ctx.fi ...

Generating Tree Structure Object Automatically from Collection using Keys

I am looking to automatically generate a complex Tree structure from a set of objects, with the levels of the tree determined by a list of keys. For example, my collection could consist of items like [{a_id: '1', a_name: '1-name', b_id ...

I am encountering an issue with Angular where the following error message is displayed: "src/app/app.component.html:18:20 - error TS2339: Property 'DepScreen' does not exist on type 'AppComponent'"

This code snippet is from my app.component.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" ...

"Encountering difficulties in establishing a new remote connection with IE11 using Protractor and

Issue with protractor conf.js opening the angular website in Internet Explorer 11 When running protractor conf.js, IE11 opens with a different URL instead of the one specified in example_spec.js. Instead of '', it opens '' (where XXXXX ...

The most effective method for calculating overhead is through the utilization of synchronous techniques

I'm currently developing a nodeJS app that heavily relies on synchronous methods, particularly for file operations and spawning child processes. I am looking to assess the impact of these blocking main thread activities in terms of overhead. What woul ...