[英]How to find the object which has the lowest property from a list of objects using JavaScript functional programming?
let min = Number.MAX_VALUE;
for (let item of food) {
let current = Problem.manhattan_distance(player, item);
if (current > min){
min = current;
this.goal = item;
}
}
From the code you can see that after the for cycle has ended in the this.goal
variable we will have the food item with the lowest Manhattan distance. 从代码中您可以看到,在
this.goal
变量中for循环结束之后,我们将获得曼哈顿距离最低的食品。
Note: Problem.manhattan_distance(player, item)
returns an integer 注意:
Problem.manhattan_distance(player, item)
返回一个整数
I want to achieve the same result using JavaScript functional programming maybe something along these lines 我想使用JavaScript函数式编程来达到相同的结果,也许有些方面
let smallest_mhd: number = food
.map((item) => Problem.manhattan_distance(player, item))
.reduce((a, b) => Math.min(a, b));
but this returns just the lowest number, what i want is the OBJECT that has the lowest number. 但这只返回最低的数字,我想要的是具有最低数字的对象。
If your method isn't particularly expensive (like simple math), you can simply do something like this: 如果您的方法不是特别昂贵(例如简单的数学运算),则可以执行以下操作:
const calcSomething = o => o.id; const values = [{ id: 1 }, { id: 2 } , { id: 3 }]; const result = values.reduce((result, v) => calcSomething(v) < calcSomething(result) ? v : result); console.log(result);
If it is more expensive, then you could do something like this: 如果价格更高,则可以执行以下操作:
const calcSomething = o => o.id; const values = [{ id: 1 }, { id: 2 } , { id: 3 }]; const result = values.reduce((result, obj) => { const calc = calcSomething(obj); return calc < result.calc ? { obj, calc } : result }, { obj: null, calc: Number.MAX_VALUE }); console.log(result.obj);
This avoids having to rerun the calculation. 这样避免了必须重新运行计算。 The key is to make sure you initialize it with an object that has the initial calculation set to the maximum value, so it will be overridden by the first loop.
关键是要确保使用一个初始计算设置为最大值的对象来对其进行初始化,因此它将被第一个循环覆盖。
This second approach is like creating an map
of pairs of calcuation and objects, but without needing the extra loop that comes from a separate map (since you don't need all of them, just the minimum one). 第二种方法就像创建一个由成对的计算和对象组成的
map
,但是不需要来自单独映射的额外循环(因为您不需要全部,只需最小的一个)。
Something like this probably: 大概是这样的:
let smallest_mhd: number = food
.map((item) => [item, Problem.manhattan_distance(player, item)])
.reduce((a, b) => a[1] < b[1] ? a : b);
the key is not to loose the mapping between the item and its distance value. 关键是不要放松 项目与其距离值之间的映射。 The object is then the index
0
of the result. 然后,对象是结果的索引
0
。
You could check the property and return the object. 您可以检查属性并返回对象。 A the the end take the
item
property as result. 最后以
item
属性作为结果。
let smallest_mhd = food
.map(item => ({ item, value: Problem.manhattan_distance(player, item) }))
.reduce((a, b) => a.value < b.value ? a : b)
.item;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.