繁体   English   中英

如何使用reduce从具有对象数组的对象数组中找到最大值

[英]How to use reduce to find maximum from array of objects with array of objects

如果我有以下

arr = [
{key: "a",
values : [{key: "aa", value: 2}, {key: "bb", value: 5}]},
{key: "b",
values : [{key: "cc", value: 7}, {key: "dd", value: 3}]}
]

如何在 javascript 中使用reduce从嵌套对象中找到最大值? 在上述情况下,答案应该是 7。

我目前能够使用循环来实现这一点:

 let max = 0; let findDataMax = function(d) { for (let i = 0; i < d.length; i++) { let currArr = d[i].values; let tempArr = [] currArr.forEach((d) => tempArr.push(+d.value)); if (Math.max(...tempArr) > max) { max = Math.max(...tempArr); } } } let arr = [ {key: "a", values: [{key: "aa", value: 2}, {key: "bb", value: 5}]}, {key: "b",values: [{key: "cc", value: 7}, {key: "dd", value: 3}]} ]; findDataMax(arr); console.log(max);

我更愿意为此使用 reduce 以外的其他方法,但如果必须这样做,则可以将累加器设置为-Infinity开始(这样与累加器相比的任何值都将大于-Infinity )。 对于数组中的每个 object,您可以通过将values数组映射到每个 object 中的value数字数组来找到最大值,然后将这些数字传播到对Math.max()的调用中。 然后,您可以比较这是否大于当前最大值,如果是,则将其作为新值返回以用作累加器,否则,使用旧的累加器值:

 const arr = [ {key: "a", values: [{ key: "aa", value: 2}, { key: "bb",value: 5}]}, {key: "b", values: [{ key: "cc", value: 7}, { key: "dd", value: 3}]} ]; const max = arr.reduce((max, {values}) => { const newMax = Math.max(...values.map(({value}) => value)); return newMax > max? newMax: max; }, -Infinity); console.log(max);

如前所述,我可能会对 .reduce() 使用不同的方法,例如.flatMap() .reduce()获取所有 object value数字,然后您可以将其传播到对Math.max()的调用中:

 const arr = [ {key: "a", values: [{ key: "aa", value: 2}, { key: "bb",value: 5}]}, {key: "b", values: [{ key: "cc", value: 7}, { key: "dd", value: 3}]} ]; const max = Math.max(...arr.flatMap(({values}) => values.map(({value}) => value))); console.log(max);

我不知道使用reduce function 是否是解决此问题的干净解决方案,但在这里你有它:

 const arr = [{ key: 'a', values: [{ key: 'aa', value: 2 }, { key: 'bb', value: 5 }] }, { key: 'b', values: [{ key: 'cc', value: 7 }, { key: 'dd', value: 3 }] }]; // O(n * b) const maxValue = arr.reduce((prev, item) => item.values.reduce((subPrev, subItem) => (subItem.value > subPrev? subItem.value: subPrev), prev), 0); console.log(maxValue); // 7

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM