john do john do - 1 year ago 71
Javascript Question

function minMax(items) { items.reduce ([smallest, current] smallest < current ? smallest : current ) };

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))]

Answer Source

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])


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download