[英]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 我有一个这样的场景,我从API请求中获得带有键的随机值(每分钟约100个),我需要执行以下操作
I have following code , but it does not remove the original array but duplicates an array with last 2 elements. 我有以下代码,但它不会删除原始数组,但会复制最后2个元素的数组。
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 将@Bergi的注释复制到代码中
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.