我有这样一种情况,我从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);
`
答案 0 :(得分:0)
将@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);