首页 > 解决方案 > 在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);

标签: javascriptarraysobjectreduce

解决方案


你基本上做你正在做的事情,只需在你正在总结的条目中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;
}


推荐阅读