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:
- Add new items to an array
- Replace items if the key already exists
- 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);
`