使用reduce es2015查找最小值和最大值

时间:2017-04-30 10:28:15

标签: javascript ecmascript-6 babel

如果我有像这样的对象数组

[{min:5,max:10,id:1}, {min:50,max:3,id:2}, {min:1,max:40,id:3}]

如何使用reduce查找min和max?我知道我可以使用泛型循环和比较,但我想探索es2015中的reduce

3 个答案:

答案 0 :(得分:3)

You can use reduce like this to get the min and max numbers from each object in the array.

const arr = [{min:5,max:10,id:1}, {min:50,max:3,id:2}, {min:1,max:40,id:3}]

console.log(
  arr.reduce((acc, x) => {
    acc.min = Math.min(acc.min, x.min)
    acc.max = Math.max(acc.max, x.max)
    return acc
  }, { min: Infinity, max: -Infinity })
)

// as Bergi suggested, we could just return a new Object literal
// from the reduction
console.log(
  arr.reduce((acc, x) => ({
    min: Math.min(acc.min, x.min),
    max: Math.max(acc.max, x.max)
  }), { min: Infinity, max: -Infinity })
)

答案 1 :(得分:0)



const arr = [{min:5,max:10,id:1}, {min:50,max:3,id:2}, {min:1,max:40,id:3}];

const min = arr.reduce((m, o) => m < o.min? m: o.min, +Infinity),
      max = arr.reduce((M, o) => M > o.max? M: o.max, -Infinity);

console.log("Min:", min);
console.log("Max:", max);
&#13;
&#13;
&#13;

min的说明:

const min = arr.reduce((m, o) => { // for each object o in the array arr
    return m < o.min?              // if o.min is bigger than the minimum m
              m:                   // then the minimum is still m
              o.min;               // otherwise, the new minimum is o.min
}, +Infinity);                     // pass in +Ifinity as the minimum (the initial value of m so whatever is arr[0].min is it will be smaller than m). You can pass in arr[0].min if you want instead of +Infinity

答案 2 :(得分:0)

Assuming that you want, for the minimum, to get the id of the item with the lowed min value, then this will do it.

const items = [{min:5,max:10,id:1}, {min:50,max:3,id:2}, {min:1,max:40,id:3}];

// Reduce to find the item with the lowest min
const min = items.reduce((res, item) => {
  // No result yet, so the item must be the lowest seen
  if (!res) return item;
  // Use the lowest of the current lowest and the current item
  return item.min < res.min ? item : res;
}, undefined).id;