Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 409
Riël Avatar asked Apr 08 '15 13:04

Riël


People also ask

How do you find the maximum absolute value in an array?

Given an unsorted array A of N integers, Return maximum value of f(i, j) for all 1 ≤ i, j ≤ N. f(i, j) or absolute difference of two elements of an array A is defined as |A[i] – A[j]| + |i – j|, where |A| denotes the absolute value of A.

Can you do absolute value in JavaScript?

abs() The Math. abs() function returns the absolute value of a number.

What is math Max in JavaScript?

The Math. max() method returns the number with the highest value.


1 Answers

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.

like image 189
Tomalak Avatar answered Oct 05 '22 21:10

Tomalak