我有一个字典数组,我正在尝试从数组中获取具有最高值的字典。
const array = [{"value": 1}, {"value": 3}, {"value": 2}]
我想获取 {"value": 3}
,因为它的“value”键值最高。
在 TypeScript 中实现这一目标的最优雅的方式是什么? 我想过先按值键对数组进行排序,但即使这样似乎也很痛苦。
答案 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);