如何使用JavaScript函数编程从对象列表中找到具有最低属性的对象? [英] How to find the object which has the lowest property from a list of objects using JavaScript functional programming?

查看:49
本文介绍了如何使用JavaScript函数编程从对象列表中找到具有最低属性的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    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;
        }
    }

从代码中您可以看到,在 this.goal 变量中for循环结束后,我们将获得曼哈顿距离最低的食品.

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.

注意: Problem.manhattan_distance(player,item)返回一个整数

我想使用JavaScript函数式编程实现相同的结果也许沿着这些思路

I want to achieve the same result using JavaScript functional programming maybe something along these lines

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.

第二种方法就像创建由成对计算和对象组成的 map 一样,但是不需要来自单独映射的额外循环(因为您不需要全部,所以只需至少一个).

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).

这篇关于如何使用JavaScript函数编程从对象列表中找到具有最低属性的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆