[英]Sort and remove everything except last n items in Array
我有一個這樣的場景,我從API請求中獲得帶有鍵的隨機值(每分鍾約100個),我需要執行以下操作
我有以下代碼,但它不會刪除原始數組,但會復制最后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);
`
將@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.