获取Javascript对象中最大的5个键/值
我是Javascript新手,正在寻找将对象中5个最大值的键放入新对象的最佳执行方式 例如,对象:获取Javascript对象中最大的5个键/值,javascript,arrays,object,Javascript,Arrays,Object,我是Javascript新手,正在寻找将对象中5个最大值的键放入新对象的最佳执行方式 例如,对象: let object= { a: 5, b: 87, c: 4, d: 33, e: 5, f: 99, g: 1, h: 10, i: 3, j: 43, }; 会回来吗 object= { b: 87, d: 33, f: 99, h: 10, j: 43, }; 我知道这可以通过循环每个项目并相互比较来实现,但我想知道是否有
let object= {
a: 5,
b: 87,
c: 4,
d: 33,
e: 5,
f: 99,
g: 1,
h: 10,
i: 3,
j: 43,
};
会回来吗
object= {
b: 87,
d: 33,
f: 99,
h: 10,
j: 43,
};
我知道这可以通过循环每个项目并相互比较来实现,但我想知道是否有更好的方法在Javascript中实现这一点以提高性能
谢谢
我知道这可以通过循环每个项目并相互比较来实现,但不知道是否有更好的方法
正如Pointy所说,这个过程本质上是迭代的,你不能避免一个循环,也不能避免至少一个小的内部循环
以下是一种最小化循环的方法,请参见注释:
// Start with an empty array
let top5 = [];
// Add [name, value] pairs to it
for (const key in object) {
const thisValue = object[key];
// Is this value greater than an existing one?
// (This is a small inner loop, hidden in the `findIndex` call.)
const index = top5.findIndex(([_, value]) => thisValue > value);
if (index !== -1) {
// Yes, insert it into the array at that location
// (There's a small loop hidden here too: copying later entries
// back one place in the array)
top5.splice(index, 0, [key, thisValue]);
// If the array is (now) > 5 entries, remove the last
if (top5.length > 5) {
top5.pop();
}
} else if (top5.length < 5) {
// The value wasn't greater than an existing one, but
// the array still needs values; add it at the end
top5.push([key, thisValue]);
}
}
// Convert back to an object
top5 = Object.fromEntries(top5);
//从空数组开始
让top5=[];
//向其中添加[名称,值]对
for(对象中的常量键){
const thisValue=对象[键];
//此值是否大于现有值?
//(这是一个小的内部循环,隐藏在'findIndex'调用中。)
const index=top5.findIndex(([[uu,value])=>thisValue>value);
如果(索引!=-1){
//是,将其插入到该位置的阵列中
//(这里也隐藏了一个小循环:复制以后的条目
//返回阵列中的一个位置)
top5.拼接(索引,0,[键,此值]);
//如果数组(现在)大于5个条目,请删除最后一个条目
如果(top5.length>5){
top5.pop();
}
}否则如果(top5.长度<5){
//该值不大于现有值,但
//数组仍然需要值;请在末尾添加它
top5.推送([键,此值]);
}
}
//转换回一个对象
top5=对象。fromEntries(top5);
现场:
let对象={
a:5,
b:87,
c:4,
d:33,
e:5,
f:99,
g:1,
h:10,
i:3,
j:43,
};
//从空数组开始
让top5=[];
//向其中添加[名称,值]对
for(对象中的常量键){
const thisValue=对象[键];
//此值是否大于现有值?
//(这是一个小的内部循环,隐藏在'findIndex'调用中。)
const index=top5.findIndex(([[uu,value])=>thisValue>value);
如果(索引!=-1){
//是,将其插入到该位置的阵列中
//(这里也隐藏了一个小循环:复制以后的条目
//返回阵列中的一个位置)
top5.拼接(索引,0,[键,此值]);
//如果数组(现在)大于5个条目,请删除最后一个条目
如果(top5.length>5){
top5.pop();
}
}否则如果(top5.长度<5){
//该值不大于现有值,但
//数组仍然需要值;请在末尾添加它
top5.推送([键,此值]);
}
}
//转换回一个对象
top5=对象。fromEntries(top5);
控制台日志(top5)代码>我会将它们转换为地图,对它们进行排序,然后取前5个并将它们转换回一个对象,下面是一个分步分解:
const对象={
a:5,
b:87,
c:4,
d:33,
e:5,
f:99,
g:1,
h:10,
i:3,
j:43,
};
const newMap=Object.entries(Object);
const sortedMap=newMap.sort((item1,item2)=>item2[1]-item1[1]);
const top5Map=sortedMap.slice(0,5)
const top5=Object.fromEntries(top5Map);
console.log(top5)
该过程本质上是迭代的;无需逃避查看属性并收集最大值的需要。请注意,这不会保留原始键顺序