程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了获取 Javascript 对象中的 5 个最大的键/值大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决获取 Javascript 对象中的 5 个最大的键/值?

开发过程中遇到获取 Javascript 对象中的 5 个最大的键/值的问题如何解决?下面主要结合日常开发的经验,给出你关于获取 Javascript 对象中的 5 个最大的键/值的解决方法建议,希望对你解决获取 Javascript 对象中的 5 个最大的键/值有所启发或帮助; @H_197_2@我是 JavaScript 新手,正在寻找将对象中 5 个最大值的键转换为新对象的最佳性能方法。

@H_197_2@例如,对象:

let object= {
  a: 5,b: 87,c: 4,d: 33,e: 5,f: 99,g: 1,h: 10,i: 3,j: 43,};
@H_197_2@会回来

object= {
  b: 87,};
@H_197_2@我知道这可以通过遍历每个项目并相互比较来完成,但想知道是否有更好的方法在 JavaScript 中执行此操作以提高性能

@H_197_2@谢谢,

解决方法

@H_197_2@我会将它们转换为地图,对它们进行排序,然后取前 5 个并将它们转换回一个对象,这是一个分步分解:

@H_197_2@
<div *ngFor="let row of rows">
  <custom-form [rowData]="row">
  </custom-form>
</div>
@H_197_2@ , @H_197_2@我知道这可以通过遍历每个项目并相互比较来完成,但想知道是否有更好的方法......

@H_197_2@正如 pointy 所说,这个过程本质上是迭代的,你无法避免一个循环,也无法避免至少一个内部循环。

@H_197_2@这是一种最小化循环的方法,请参阅评论:

// 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,[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);
@H_197_2@直播:

@H_197_2@
let object= {
  a: 5,b: 87,c: 4,d: 33,e: 5,f: 99,g: 1,h: 10,i: 3,j: 43,};
// Start with an empty array
let top5 = [];
// Add [name,thisValue]);
    }
}
// Convert BACk to an object
top5 = Object.fromEntries(top5);
console.log(top5);
@H_197_2@ @H_197_2@请注意,top5 总是以最高值在前排列,如果 value 低于我们知道的最高值,则通过尽早淘汰 androidExtensions { experimental = true } 来最小化我们必须进入数组的距离(数组中的第一个)。

@H_197_2@我没有尝试保留属性顺序,尤其是因然属性有顺序(现在),但依赖该顺序几乎总是一个坏主意。

大佬总结

以上是大佬教程为你收集整理的获取 Javascript 对象中的 5 个最大的键/值全部内容,希望文章能够帮你解决获取 Javascript 对象中的 5 个最大的键/值所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。