简体   繁体   中英

Sort and remove everything except last n items in Array

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

  1. Push new items to the array
  2. Replace items if key is duplicate
  3. 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); 

`

Copied @Bergi 's comment into code

 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 keys.slice(0, -2).forEach(key => stats.delete(key)) stats = keys.map(key => { return { key: key, value: stats.get(key) }; }); console.log(stats); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM