-2

I am calling reduce two times to get the min and max but insted is there a way that i can call reduce only onetime and get the same result - Must do this by using a single call to reduce. - For example, minMax([4, 1, 2, 7, 6]) returns [1, 7]

function minMax(items) 
{
    return [items.reduce((prev, curr)=> Math.min(prev, curr)),
            items.reduce((prev, curr)=> Math.max(prev, curr))]
}
john do
  • 3
  • 2
  • Please give an actual title... – Andrew Li Oct 08 '16 at 00:54
  • 1
    Just use `return [Math.min(...items), Math.max(...items)]`. – Sebastian Simon Oct 08 '16 at 01:18
  • @Xufox Nice :),, The only thing is the OP says -> `Must do this by using a single call to reduce`. I'm not sure why it had to be, but out of curiosity I thought I'd do some quick performance tests, and using reduce was more than twice as fast. I'm assuming it's not just down to the fact that reduce is doing a single pass either, but doing it in a single pass will help with CPU caching. But anyway, regardless I still think your answer deserves a thumbs up.. :) – Keith Oct 08 '16 at 17:01

2 Answers2

0

It's possible to work with reduce on more than one thing at a time, the inital value can be anything, arrays / objects etc.

Below should be something what your after.

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));
Keith
  • 22,005
  • 2
  • 27
  • 44
0

Just use Math min and max with apply bound to Math ;)

const nums = [4, 1, 2, 7, 6];

const minMax = numbers => [Math.min.apply(Math, numbers), Math.max.apply(Math, numbers)];

console.log(minMax(nums));
cstuncsik
  • 2,698
  • 2
  • 16
  • 20