打字稿:在具有最高键值的字典数组中获取字典

时间:2021-04-27 16:54:03

标签: typescript

我有一个字典数组,我正在尝试从数组中获取具有最高值的字典。

const array = [{"value": 1}, {"value": 3}, {"value": 2}]

我想获取 {"value": 3},因为它的“value”键值最高。

在 TypeScript 中实现这一目标的最优雅的方式是什么? 我想过先按值键对数组进行排序,但即使这样似乎也很痛苦。

1 个答案:

答案 0 :(得分:1)

你可以这样做。 Playground

   interface Value {
    value: number;
}

    const array:Value[] = [{ "value": 1 }, { "value": 3 }, { "value": 11 }, { "value": 0 }, { "value": 8 }, { "value": 10 }];
    
    const greatest = array.reduce((accumulator: Value, element: Value) => {
        if (accumulator["value"] > element["value"])
            return accumulator;
        return element;
    });
    
    console.log(greatest);