Filter out items in the Array, leaving only the last n elements and arranging them in

In my current scenario, I am receiving random values with keys from an API request at a rate of about 100 per minute. My goal is to perform the following actions:

  1. Add new items to an array
  2. Replace items if the key already exists
  3. Sort the original Map and only keep the last n elements in the array

The code snippet I have below does not achieve the desired outcome as it duplicates an array with just the last 2 elements instead of removing elements from the original array.

var stats = new Map([['22',10],['32',3],['42',22],['52',7]]);
// Dynamic values are set inside an AJAX function, which may be duplicates or new entries
stats.set('22', 20);
stats.set('12', 20);
// Sort by key
var keys = Array.from(stats.keys());
keys.sort();
// Get the last two keys
keys = keys.slice(-2);
// Map the remaining keys to the desired structure
var result = keys.map(key => { 
  return { 
    key: key, 
    value: stats.get(key) 
  }; 
});
console.log(result); 

`

Answer №1

Pasted @Bergi 's comment as code snippet

var data = new Map([['22',10],['32',3],['42',22],['52',7]]);
   // Injecting dynamic values within an ajax function, which can be duplicates or new items
            data.set('22', 20);
            data.set('12', 20);
            // Sorting by key
            var keysArr = Array.from(data.keys());
            keysArr.sort();
            // Fetch and store the last two items
            keysArr = keysArr.slice(-2);
            // Converting the remaining keys into a desired structure
            keysArr.slice(0, -2).forEach(key => data.delete(key))
            data = keysArr.map(key => { 
              return { 
                key: key, 
                value: data.get(key) 
              }; 
            });
            
            console.log(data);

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

Substitute the specified user within a secure range using a script on Google Sheets

My specific scenario is as follows: I have certain ranges protected in Google Sheets I need to replace a specific editor if they are an editor of those ranges (var Editor2Replace and Editor2Add are emails) Naturally, I attempted the following for each she ...

Using Promise, async, and await, even if the Boolean value returned is false, the condition will still be

Context Within my code, I have implemented a function to ensure app updates by checking if an update is necessary. The function should return true or false based on the comparison between the user's current app version and the App Store version. It f ...

Error: The method 'editable' is not defined for the jQuery.jEditable object [object Object]

It seems like there is an error with this jeditable object. This is my webpage <script src="/assets/jquery.js?body=1" type="text/javascript"></script> <script src="/assets/jquery_ujs.js?body=1" type="text/javascript"></script> .. ...

utilizing AJAX in PHP for a dynamic selection process with MariaDB

I am working on a dynamic select feature using AJAX, PHP, and queries to a database. There are three main components involved in this process: the HTML where the select options are populated from database queries done through AJAX, the PHP scripts that han ...

Creating a collection of cell values

I am dealing with a large array of strings that is formatted as ['name1';'name2';...], where the names vary in length. I understand that I need to utilize cells in MATLAB, but I am struggling to implement it for this specific scenario. ...

Divide a compound element of TextNodes and elements by utilizing jQuery

Looking for a way to split an HTML element based on user selection using jQuery? Check out the example below with square brackets indicating the selection: Lor[em <a>ips]um <span>dolor</span></a> The desired output should be: Lor ...

The .ajaxSubmit function in jquery.form.js seems to be malfunctioning when using the data option

I'm currently working with the jQuery plugin jquery.form.js and I'm looking to programmatically submit a form while including a file. Although I've set up the code and options to work with $.ajax, it's not functioning with .ajaxSubmit. ...

Exploring Head-Linked/Off-center View in Three.js

I'm attempting to create a permanent head-coupled perspective without relying on the full headtrackr library. My head will remain stationary, but it will not be directly facing the screen. For those interested, I have a small demonstration available ...

Utilizing AngularJS and RequireJS to incorporate a controller into the view

I am facing an issue while trying to add an Angular controller to my HTML view. Typically, in Angular, this can be done using: ng-controller="<controller>". However, due to my use of RequireJS, I have had to implement it differently. I need to includ ...

`What is the best way to adjust scroll position using jQuery?`

After encountering a similar issue with locking the vertical scroll while opening a mobile menu on a website I'm working on, I came across a potential solution HERE. However, despite trying to implement it, I haven't been successful. The main pro ...

Mapping data visually

Currently, I am in the midst of a vuejs project where I aim to create data visualizations on a map. My goal is to showcase a world map with percentages representing each country. However, I find myself at a loss on how to begin this task. Are there any r ...

Identify regions with identical values within a 2D array

I have a 2D array that looks like the following: 1 1 1 0 0 0 0 1 1 1 1 0 1 0 1 0 0 0 1 1 0 0 0 0 1 If I select a random position, for example [4, 2], I want the array to change to: X X X X X 0 0 X X X X 0 X 0 X 0 0 0 X X 0 0 0 0 X Can anyone provide an ...

Read through the text, determine the length of each word, and keep track of how

Objective: Create a JavaScript program that takes input from users in the form of several lines of text and generates a table displaying the count of one-letter words, two-letter words, three-letter words, etc. present in the text. Below is an example ou ...

An optimal method for retrieving data from a database using an array

I am facing a performance issue with querying my database using an array of about 400 single string number items. The current implementation takes around 4-6 seconds to load the page, which is not efficient. I am looking for a better way to handle this s ...

javascript issue with attribute manipulation

My current struggle involves setting the attribute of an element through programming, but I keep encountering an error in Firebug: obj.setAttribute is not a function. Since I am working with jQuery, allow me to provide some additional code for better conte ...

Encountered an issue while attempting to handle the image uploaded via React using Node.js and Sharp

I have integrated a feature to allow users to upload their profile picture using the frontend, which is functioning properly. However, the backend keeps rejecting the uploaded image files, even if they are in jpeg, jpg, or png format. const storage = multe ...

Creating a robust system for resetting passwords using the powerful combination of Django Rest Framework, Serializers, and Vue.js

I am currently in the process of implementing a reset password feature, but I am struggling to find comprehensive tutorials on how to do so using DRF and Vue.js. My approach involves utilizing serializers for data passing without incorporating HTML views. ...

How to efficiently retrieve a form's data from multiple forms with identical ids in JavaScript

I am facing a challenge with multiple forms on the html page that have the same ID. I need to send each form's information to the server based on user selection, but I haven't been able to find a relevant solution. For my Authorization polic ...

to flip the order of the elements in an array

Below is the code I wrote to reverse the elements in an array: public class Reversal { public static void main(String[] args) { Scanner input = new Scanner(System.in); int number = input.nextInt(); int[] array = new int[number] ...

Loop through page.evaluate in Nodejs

Currently, I am attempting to utilize the for-of looping method in order to iterate through an array of URLs and apply them with the page.evaluate function from the puppeteer library. To simplify my process, I will share a snippet of my code (with a sing ...