9

I am looking for a nice way to find the maximum ABSOLUTE value of an array.

My array is i.e.

var array = [10,20,40,-30,-20,50,-60];

Then:

Math.max.apply(null,array);

Will result in '50'. But, actually, I want it to return '60'.

The option is to create a second array using Math.abs, but actually I am wondering if the apply function can be combined, so it is one elegant solution.

Riël
  • 1,251
  • 1
  • 16
  • 31

3 Answers3

24
Math.max.apply(null, array.map(Math.abs));

If you target browsers that don't support Array.prototype.map (IE<=8), use the polyfill or a library like sugar.js.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
3

Try this:

var array = [10,20,40,-30,-20,50,-60];
var absMax = array.reduce(function(max, item){
    return Math.max(Math.abs(max),Math.abs(item));
});
v1vendi
  • 603
  • 4
  • 9
  • Thank you, the above answer is a bit more elegant, but yours had gave me some nice 'aha'. Still lot to learn about JS. – Riël Apr 08 '15 at 13:46
3

How this

var array = [10,20,40,-30,-20,50,-60];    
return Math.max(...array.map(a => Math.abs(a)))