I have a scenario like this , I get random values with key from an API request (around 100 per minute) , I need to do the following
- Push new items to the array
- Replace items if key is duplicate
- Sort the original Map and remove everything except last n elements in original array
I have following code , but it does not remove the original array but duplicates an array with last 2 elements.
      var stats = new Map([['22',10],['32',3],['42',22],['52',7]]);
   // I set dynamic values like below inside ajax function , can be duplicate or new
            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.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); `
 
    