Search code examples
javascriptarraysmathmaxabsolute

Find absolute max value in Javascript array


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.


Solution

  • 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.