javascript - 在reduce函数javascript中找到最大值和最小值
问题描述
如何在reduce函数中找到最大值和最小值。我可以在数据集中对“a”和“b”求和,但我找不到最大值a和最小值b并将其添加到同一个列表中
var liste = [
{"id":1,"a":5,"b":4},
{"id":1,"a":2,"b":2},
{"id":1,"a":7,"b":1},
{"id":1,"a":1,"b":0},
{"id":2,"a":11,"b":5},
{"id":2,"a":32,"b":75},
{"id":3,"a":1,"b":1},
{"id":4,"a":1,"b":1},
{"id":4,"a":213,"b":1},
{"id":5,"a":1,"b":1},
{"id":5,"a":1,"b":1},
]
var max = 0;
let map = liste.reduce((prev, next) => {
if (next.id in prev) {
prev[next.id].a += next.a;
prev[next.id].b += next.b;
if(next.a > max){
max = next.a;
prev[next.id].max = max;
}
} else {
prev[next.id] = next;
next.max =max
}
return prev;
}, {});
let result = Object.keys(map).map(id => map[id]);
console.log(result);
解决方案
你基本上做你正在做的事情,只需在你正在总结的条目中a
包含最大值。b
但这reduce
是错误的工具,您所需要的只是一个简单的for-of
循环。(你可以把它硬塞进一个reduce
调用中,因为基本上任何数组操作都可以塞进一个reduce
调用中,但是除了复杂性之外它不会给你带来任何好处。)我也会使用一个Map
而不是一个空白对象进行查找(但是一个object 也可以;当为此使用对象时,我通常建议通过Object.create(null)
) 创建没有原型的对象。
const map = new Map();
for (const entry of liste) {
const {id, a, b} = entry;
// Do we have an entry for this ID?
let known = map.get(id);
if (!known) {
// No, use this one (note: I would make a copy rather than modifying the original)
known = entry;
map.set(id, entry);
// Initialize its max with the values from this entry
entry.max_a = a;
entry.max_b = b;
} else {
// Update our max values
known.max_a = Math.max(known.max_a, a);
known.max_b = Math.max(known.max_b, b);
// Add in the current entries to the sum
known.a += a;
known.b += b;
}
}
// Show the result
console.log([...map.values()]);
现场示例:
var liste = [
{"id":1,"a":5,"b":4},
{"id":1,"a":2,"b":2},
{"id":1,"a":7,"b":1},
{"id":1,"a":1,"b":0},
{"id":2,"a":11,"b":5},
{"id":2,"a":32,"b":75},
{"id":3,"a":1,"b":1},
{"id":4,"a":1,"b":1},
{"id":4,"a":213,"b":1},
{"id":5,"a":1,"b":1},
{"id":5,"a":1,"b":1},
]
const map = new Map();
for (const entry of liste) {
const {id, a, b} = entry;
// Do we have an entry for this ID?
let known = map.get(id);
if (!known) {
// No, use this one (note: I would make a copy rather than modifying the original)
known = entry;
map.set(id, entry);
// Initialize its max with the values from this entry
entry.max_a = a;
entry.max_b = b;
} else {
// Update our max values
known.max_a = Math.max(known.max_a, a);
known.max_b = Math.max(known.max_b, b);
// Add in the current entries to the sum
known.a += a;
known.b += b;
}
}
// Show the result
console.log([...map.values()]);
.as-console-wrapper {
max-height: 100% !important;
}
推荐阅读
- python - Python 中的 __peg_parser__ 是什么?
- python-3.x - 如何从bash脚本中获取python文件的变量
- vue.js - 无法解析三个 gltf-loader 中的“三个”
- java - 尝试遍历 XML 文件中非常相似的元素。注意 XML 文件没有属性
- python - Python - 从电子表格中的列中提取数据时条件语句不起作用
- amazon-web-services - 尝试安装 AWS Elastic Beanstalk 获取:ObjectNotFound: (C:\Users\Ameer:String) [], CommandNotFoundException
- javascript - 如何在 NodeJS 中使用 fs 删除扩展名未知的文件?
- prometheus - prometheus federation 集群数据同步逻辑
- python - ModuleNotFoundError 尽管在 VSCode 中安装了软件包并选择了正确的解释器
- chisel - 使用带有命名空间机制的 chisel3?