gpt4 book ai didi

javascript - 返回具有某些属性最大值的数组中的对象不是低效方法吗?

转载 作者:行者123 更新时间:2023-12-02 17:55:21 25 4
gpt4 key购买 nike

我觉得这是重复的和/或低效的:

self.get_max_dist = function(array) {

var arr = array.map(function(value) {
return value.distance;
});

var max = Math.max.apply(null, arr);

return array.filter(function(el) {
return el.distance === max;
});

};

如何消除我的感觉?

示例数组:

[
{
distance: 256.62,
maxspeed: 340.65,
pid: "675",
prestrafe: 275.626
},

...

]

最佳答案

执行效率可能是通过一次遍历数组而不是代码中的三遍来实现的。这是一个一次性解决方案:

self.get_max_dist = function(array) {
var output = [], max = 0, item;
for (var i = 0; i < array.length; i++) {
item = array[i];
if (item.distance > max) {
// new max value so initialize
// output starting with this item
output = [item];
max = item.distance;
} else if (item.distance === max) {
// found another item with our max value
// so add it to the current output
output.push(item);
}
}
return output;
}

为了简化编码,假设距离不为负。如果您不希望出现这种假设,可以添加几行代码来处理该问题。

<小时/>

如果您只想获取单个最大距离项目,则可以更简单一点:

self.get_max_dist = function(array) {
var max, item;
for (var i = 0; i < array.length; i++) {
item = array[i];
if (!max || (item.distance > max.distance)) {
max = item;
}
}
return max;
}
<小时/>

或者,如果您喜欢迭代器,最后一个可以是:

self.get_max_dist = function(array) {
var max;
array.foreach(function(item) {
if (!max || (item.distance > max.distance)) {
max = item;
}
});
return max;
}

关于javascript - 返回具有某些属性最大值的数组中的对象不是低效方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21002447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com