【问题标题】:function minMax(items) { items.reduce ([smallest, current] smallest < current ? smallest : current ) };function minMax(items) { items.reduce ([smallest, current] minimum < current ? minimum : current ) };
【发布时间】:2016-10-08 00:52:16
【问题描述】:

我调用reduce 两次以获得最小值和最大值,但是有没有一种方法可以让我只调用reduce 一次并获得相同的结果 - 必须通过使用单个调用来减少。 - 例如 minMax([4, 1, 2, 7, 6]) 返回 [1, 7]

function minMax(items) 
{
    return [items.reduce((prev, curr)=> Math.min(prev, curr)),
            items.reduce((prev, curr)=> Math.max(prev, curr))]
}

【问题讨论】:

  • 请给出一个实际的标题...
  • 只需使用return [Math.min(...items), Math.max(...items)]
  • @Xufox Nice :),, 唯一的事情是 OP 说 -> Must do this by using a single call to reduce。我不确定为什么会这样,但出于好奇,我想我会做一些快速的性能测试,使用 reduce 的速度是原来的两倍多。我假设这不仅仅是因为reduce 正在执行单程,而且单程执行将有助于CPU 缓存。但无论如何,无论如何,我仍然认为你的回答值得竖起大拇指.. :)

标签: javascript functional-programming computer-science


【解决方案1】:

reduce 可以一次处理不止一件事情,初始值可以是任何东西,数组/对象等。

下面应该是你想要的东西。

var values = [33,2,48,23,1,45,23,311,312,32,32]

function minMax(items) { 
 return items.reduce(function (a,b) { 
      a[0] = Math.min(a[0], b), 
      a[1] = Math.max(a[1], b); 
      return a; }, 
    [+Infinity, -Infinity])
}

console.log(minMax(values));

【讨论】:

    【解决方案2】:

    只需使用数学最小值和最大值并将应用绑定到数学;)

    const nums = [4, 1, 2, 7, 6];
    
    const minMax = numbers => [Math.min.apply(Math, numbers), Math.max.apply(Math, numbers)];
    
    console.log(minMax(nums));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-15
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      相关资源
      最近更新 更多