1141

How can I easily obtain the min or max element of a JavaScript array?

Example pseudocode:

let array = [100, 0, 50]

array.min() //=> 0
array.max() //=> 100
varad_s
  • 764
  • 1
  • 12
  • 24
HankH
  • 11,453
  • 4
  • 17
  • 4
  • 170
    **Note:** With ECMAScript 6 you can use the new [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator) (three dots: `...`) with `Math.max()` like this: `Math.max(...[2, 5, 16, 1])`. See [my answer](http://stackoverflow.com/a/30834687) made from the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max#Examples). – totymedli Jun 14 '15 at 21:26
  • here a benchmark for a speed comparison of the most common ways to do it: http://jsben.ch/#/1QuTg – EscapeNetscape Oct 25 '16 at 08:46
  • **Without ES6** `Math.max.apply(null, [2,5,16,1])` – Tomer Nov 27 '19 at 14:20
  • 2
    In ES6, obtaining both the maximum and minimum can be [done with only one `reduce` call](https://stackoverflow.com/a/63514134/9513184). – Unmitigated Aug 21 '20 at 14:13
  • @totymedli 's solution of using the spread operator is not a good idea. If the array is too large, this will cause a stack overflow exception (too many parameters being passed to the function). A much better idea is ot use `reduce` – Aron Fiechter Oct 13 '21 at 13:39
  • 1
    @AronFiechter Did you actually read my answer? I explain all the options in great detail with code examples and benchmarks. The call stack size is only a problem if your arrays have a size larger than 100000. While the call stack has to be considered, in most cases it won't be an issue and the more concise code outweighs the drawbacks. – totymedli Oct 13 '21 at 22:12
  • 1
    This call stack may be an issue. There's a HackerRank question that requires finding min and max, and the tests run under a limit of 10 seconds. The arrays passed in by HackerRank for the 9th to 14th tests have lengths of >100,000; and will fail if the reduce solution in the answer below is used. The for-loop will pass for some – orimdominic Dec 07 '21 at 08:52
  • Use ```...```(spread operator): ```const maxValue = Math.max(...array))``` – chickens Aug 03 '22 at 22:01

60 Answers60

1075

How about augmenting the built-in Array object to use Math.max/Math.min instead:

Array.prototype.max = function() {
  return Math.max.apply(null, this);
};

Array.prototype.min = function() {
  return Math.min.apply(null, this);
};

let p = [35,2,65,7,8,9,12,121,33,99];

console.log(`Max value is: ${p.max()}` +
  `\nMin value is: ${p.min()}`);

Here is a JSFiddle.

Augmenting the built-ins can cause collisions with other libraries (some see), so you may be more comfortable with just apply'ing Math.xxx() to your array directly:

var min = Math.min.apply(null, arr),
    max = Math.max.apply(null, arr);

Alternately, assuming your browser supports ECMAScript 6, you can use spread syntax which functions similarly to the apply method:

var min = Math.min( ...arr ),
    max = Math.max( ...arr );
RobG
  • 142,382
  • 31
  • 172
  • 209
Roatin Marth
  • 23,589
  • 3
  • 51
  • 55
  • 2
    Shouldn't that be "return Math.max.apply( Math, this );" and not return Math.max.apply( null, this ); – HankH Nov 03 '09 at 18:24
  • 4
    @HankH: maybe. `Math.max` is akin to a "static" method, so there is no useful `this` instance inside of it (I hope). So assuming that is true, calling it would run it in the global scope (i.e. `window`), which is equivalent to passing `null` as the first paramter to `apply`/`call`. – Roatin Marth Nov 03 '09 at 18:26
  • 9
    @HankH: passing `null` or `Math` or `{}` or whatever to `apply()` or `call()` has no bearing on the outcome. `Math.max` does not nor should not reference `this` internally. – Roatin Marth Nov 03 '09 at 18:43
  • 2
    @ChaosPandion: you are absolutely right. This does not work on any other type. – Roatin Marth Nov 03 '09 at 18:46
  • 1
    This is a great theoretical answer, but in practice has some flaws. Big arrays return different arrays for Node.js and Chrome. Better solutions for big arrays are presented below, not so fancy, but stronger than this one. – Alejandro Rizzo May 04 '12 at 19:03
  • 7
    Just sharing a jQuery mistake I was making with the code above which took me a long time to debug. A jquery array works fine on everything but the iPad. I had to convert the array to a true native array for it to work. Only affected the single device for some reason `Math.max.apply(null, $.makeArray(array));` – Forrest Jul 25 '12 at 21:17
  • 1
    @Forrest: what is a "jquery array"? – Roatin Marth Apr 05 '13 at 16:39
  • @RoatinMarth It's an "array-like object", like what is returned from finding DOM-elements with the jQuery selector. Read [jQuery's explanation of the makeArray function](https://api.jquery.com/jQuery.makeArray/). – zykadelic Mar 11 '14 at 14:50
  • 20
    I've downvoted, because proposed approach consumes O(n) memory in stack frame, and as a result crashes on large arrays. In my case just about 130000 numbers were enough to crash nodejs. – Alexey Timanovsky Feb 12 '15 at 12:11
  • 37
    Don't augment built-in prototypes like this. It's not just about conflicts with other libraries; it's also about the potential that the browser itself provides a `.max` or `.min` method in future. Perfectly realistic scenario: *You use this answer. In 2016, ES7 or ES8 spec `Array.max` and `Array.min`. Unlike this version, they work on strings. Your future colleague tries to get the alphabetically-latest string in an array with the now-well-documented native `.max()` method, but mysteriously gets `NaN`. Hours later, she finds this code, runs a `git blame`, and curses your name.* – Mark Amery Feb 14 '15 at 00:21
  • 4
    ... or just wrap code `if (!Array.max) { ... } ` so that if browser ever does add these methods they don't get replaced. – nothingisnecessary Dec 14 '16 at 00:38
  • 1
    Note that this has a length limit because all values are passed as arguments. I run some tests on my pc, `Math.max` could accept up to 100,000 arguments on Chrome, 300,000 on Firefox, 400,000 on Edge, 150,000 on IE11 (tested on Win10, all browsers latest). – oriadam Nov 26 '18 at 08:26
  • This is a very slow method, what if array would have thousands of elements? – Slava Fomin II Mar 22 '19 at 21:57
  • This also fails if any element is NaN, undefined, null or the array is sparse (i.e. not contiguous, e.g. `[,1,2].max()` returns *NaN*). – RobG Jun 09 '22 at 14:33
  • Why change the prototype of a primitive object when you can just create a function that accepts an array and doesn't have side effects on the entire environment in which your code operates? – Joel M Dec 03 '22 at 21:07
454
var max_of_array = Math.max.apply(Math, array);

For a full discussion see: http://aaroncrane.co.uk/2008/11/javascript_max_api/

GSerg
  • 76,472
  • 17
  • 159
  • 346
newspire
  • 6,144
  • 2
  • 17
  • 12
  • 21
    What is the difference between `Math.max.apply(Math, array)` and `Math.max.apply(null, array)`? The blog says "...you also have to redundantly say again that `max` belongs to `Math`...", but it seems I don't have to do so (by setting the first argument of `apply` as `null`). – Ziyuan Dec 21 '15 at 13:45
  • 15
    @ziyuang When you call it like `Math.max(a,b)`, `Math` is passed as the `this` value, so it might make sense to do the same when calling with `apply`. But `Math.max` does not use the `this` value, so you can pass whatever value you want. – Oriol Dec 10 '16 at 09:45
332

Using spread operator (ES6)

Math.max(...array)  // The same with "min" => Math.min(...array)

const array = [10, 2, 33, 4, 5];

console.log(
  Math.max(...array)
)
Gass
  • 7,536
  • 3
  • 37
  • 41
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • 13
    This solution was already provided by [multiple](http://stackoverflow.com/a/30834687/1494454) [other](http://stackoverflow.com/a/27537882/1494454) answers. – totymedli Apr 13 '17 at 22:40
  • 47
    Math.max(...[]) = -Infinity. hahaha – David Portabella Mar 09 '18 at 11:00
  • 9
    @DavidPortabella not sure why that's funny. That's how it works [according to the specification](https://tc39.github.io/ecma262/#sec-math.max): `If no arguments are given, the result is -∞.` – Patrick Roberts Jul 17 '18 at 18:01
  • 10
    yes, I meant that the javascript specification is horrible. It seems obvious that the min of no numbers cannot be computed. In other more serious programming languages, such as Scala, asking for the min of an empty array throws an exception. – David Portabella Jul 18 '18 at 13:45
  • This is a very slow method, what if array would have thousands of elements? – Slava Fomin II Mar 22 '19 at 21:56
  • Doesn't work with array of Date strings. Use `dates.reduce(function (a, b) { return a > b ? a : b; });` – Jan Jul 02 '20 at 11:27
  • @totymedli : the differentiator in this answer is that one line .. no need to waste reader time :) – Abdennour TOUMI Dec 30 '20 at 10:16
  • what would be the time complexity of this solution using the spread operator? – medev21 May 10 '21 at 00:27
  • Not sure if the builtin Math.max function would be faster with infinity values. haha – Mpwanyi Samuel Dec 10 '21 at 11:28
286

For big arrays (~10⁷ elements), Math.min and Math.max both produces the following error in Node.js.

RangeError: Maximum call stack size exceeded

A more robust solution is to not add every element to the call stack, but to instead pass an array:

function arrayMin(arr) {
  return arr.reduce(function (p, v) {
    return ( p < v ? p : v );
  });
}

function arrayMax(arr) {
  return arr.reduce(function (p, v) {
    return ( p > v ? p : v );
  });
}

If you are concerned about speed, the following code is ~3 times faster then Math.max.apply is on my computer. See https://jsben.ch/JPOyL.

function arrayMin(arr) {
  var len = arr.length, min = Infinity;
  while (len--) {
    if (arr[len] < min) {
      min = arr[len];
    }
  }
  return min;
};

function arrayMax(arr) {
  var len = arr.length, max = -Infinity;
  while (len--) {
    if (arr[len] > max) {
      max = arr[len];
    }
  }
  return max;
};

If your arrays contains strings instead of numbers, you also need to coerce them into numbers. The below code does that, but it slows the code down ~10 times on my machine. See https://jsben.ch/uPipD.

function arrayMin(arr) {
  var len = arr.length, min = Infinity;
  while (len--) {
    if (Number(arr[len]) < min) {
      min = Number(arr[len]);
    }
  }
  return min;
};

function arrayMax(arr) {
  var len = arr.length, max = -Infinity;
  while (len--) {
    if (Number(arr[len]) > max) {
      max = Number(arr[len]);
    }
  }
  return max;
};
EscapeNetscape
  • 2,892
  • 1
  • 33
  • 32
Linus Unnebäck
  • 23,234
  • 15
  • 74
  • 89
  • assign `min` and `max` to last element and reduce the iterations by 1 (`while(--len)`) ;) – Venugopal Dec 30 '15 at 11:21
  • @Venugopal then you need a special check to see if the array is empty and return +/- Infinity – Linus Unnebäck Dec 31 '15 at 07:27
  • 3
    Strange... I went to the linked website... and testing in Firefox 51.0.0 / Mac OS X 10.12.0, the reduce-based approach is 30% slower than loop-based ... very different results – Pierpaolo Cira Feb 21 '17 at 09:37
  • https://jsperf.com/array-min-max-random/1 starting from 60 elements Math methods are breaking equal with while cycles, if array size is greater than 60, than Math methods wins. Larger the array - greater the Math methods overtake. ( for 100 elems Math.min/max is 10% faster, for 1000 elems its +25% ) – Алексей Лещук Apr 19 '18 at 07:31
  • Yes you should add a quick check and assign one element of the array to min and max, because just assign a very extreme value maybe fine for most applications, but it is not fully correct. A expected behavior would be: get the min or max (and nothing else) or an error/exception (e.g. if the array is empty). But just return +-inf would be wrong. (and an extra check after every usage have to be implemented.) – Horitsu Nov 01 '18 at 08:58
  • 3
    **In 2019** the `reduce` solution is the slowest. Even if you work with an array that has millions of elements, it is **better to use the standard for loop**. [See my answer for more.](https://stackoverflow.com/a/30834687/1494454) – totymedli Mar 26 '19 at 18:35
175

tl;dr

// For regular arrays:
var max = Math.max(...arrayOfNumbers);

// For arrays with tens of thousands of items:
let max = testArray[0];
for (let i = 1; i < testArrayLength; ++i) {
  if (testArray[i] > max) {
    max = testArray[i];
  }
}

MDN solution

The official MDN docs on Math.max() already covers this issue:

The following function uses Function.prototype.apply() to find the maximum element in a numeric array. getMaxOfArray([1, 2, 3]) is equivalent to Math.max(1, 2, 3), but you can use getMaxOfArray() on programmatically constructed arrays of any size.

function getMaxOfArray(numArray) {
    return Math.max.apply(null, numArray);
}

Or with the new spread operator, getting the maximum of an array becomes a lot easier.

var arr = [1, 2, 3];
var max = Math.max(...arr);

Maximum size of an array

According to MDN the apply and spread solutions had a limitation of 65536 that came from the limit of the maximum number of arguments:

But beware: in using apply this way, you run the risk of exceeding the JavaScript engine's argument length limit. The consequences of applying a function with too many arguments (think more than tens of thousands of arguments) vary across engines (JavaScriptCore has hard-coded argument limit of 65536), because the limit (indeed even the nature of any excessively-large-stack behavior) is unspecified. Some engines will throw an exception. More perniciously, others will arbitrarily limit the number of arguments actually passed to the applied function. To illustrate this latter case: if such an engine had a limit of four arguments (actual limits are of course significantly higher), it would be as if the arguments 5, 6, 2, 3 had been passed to apply in the examples above, rather than the full array.

They even provide a hybrid solution which doesn't really have good performance compared to other solutions. See performance test below for more.

In 2019 the actual limit is the maximum size of the call stack. For modern Chromium based desktop browsers this means that when it comes to finding min/max with apply or spread, practically the maximum size for numbers only arrays is ~120000. Above this, there will be a stack overflow and the following error will be thrown:

RangeError: Maximum call stack size exceeded

With the script below (based on this blog post), by catching that error you can calculate the limit for your specific environment.

Warning! Running this script takes time and depending on the performance of your system it might slow or crash your browser/system!

let testArray = Array.from({length: 10000}, () => Math.floor(Math.random() * 2000000));
for (i = 10000; i < 1000000; ++i) {
  testArray.push(Math.floor(Math.random() * 2000000));
  try {
    Math.max.apply(null, testArray);
  } catch (e) {
    console.log(i);
    break;
  }
}

Performance on large arrays

Based on the test in EscapeNetscape's comment I created some benchmarks that tests 5 different methods on a random number only array with 100000 items.

In 2019, the results show that the standard loop (which BTW doesn't have the size limitation) is the fastest everywhere. apply and spread comes closely after it, then much later MDN's hybrid solution then reduce as the slowest.

Almost all tests gave the same results, except for one where spread somewhy ended up being the slowest.

If you step up your array to have 1 million items, things start to break and you are left with the standard loop as a fast solution and reduce as a slower.

JSPerf benchmark

jsperf.com benchmark results for different solutions to find the min/max item of an array

JSBen benchmark

jsben.com benchmark results for different solutions to find the min/max item of an array

JSBench.me benchmark

jsbench.me benchmark results for different solutions to find the min/max item of an array

Benchmark source code

var testArrayLength = 100000
var testArray = Array.from({length: testArrayLength}, () => Math.floor(Math.random() * 2000000));

// ES6 spread
Math.min(...testArray);
Math.max(...testArray);

// reduce
testArray.reduce(function(a, b) {
  return Math.max(a, b);
});
testArray.reduce(function(a, b) {
  return Math.min(a, b);
});

// apply
Math.min.apply(Math, testArray);
Math.max.apply(Math, testArray);

// standard loop
let max = testArray[0];
for (let i = 1; i < testArrayLength; ++i) {
  if (testArray[i] > max) {
    max = testArray[i];
  }
}

let min = testArray[0];
for (let i = 1; i < testArrayLength; ++i) {
  if (testArray[i] < min) {
    min = testArray[i];
  }
}

// MDN hibrid soltuion
// Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply#Using_apply_and_built-in_functions
function minOfArray(arr) {
  var min = Infinity;
  var QUANTUM = 32768;

  for (var i = 0, len = arr.length; i < len; i += QUANTUM) {
    var submin = Math.min.apply(null, arr.slice(i, Math.min(i + QUANTUM, len)));
    min = Math.min(submin, min);
  }

  return min;
}

minOfArray(testArray);

function maxOfArray(arr) {
  var max = -Infinity;
  var QUANTUM = 32768;

  for (var i = 0, len = arr.length; i < len; i += QUANTUM) {
    var submax = Math.max.apply(null, arr.slice(i, Math.max(i + QUANTUM, len)));
    max = Math.max(submax, max);
  }

  return max;
}

maxOfArray(testArray);
totymedli
  • 29,531
  • 22
  • 131
  • 165
  • If you're using typescript the spread operator as shown is compiled to `Math.max.apply(Math, arr)` for 'max' compatibility. – Simon_Weaver Sep 03 '18 at 00:42
  • 2
    Also from MDN: "both spread `(...)` and `apply` will either fail or return the wrong result if the array has too many elements [...] The reduce solution does not have this problem" Testing Chrome, FF, Edge and IE11 it seems that it is ok for an array of up to 100k values. (Tested on Win10 and latest browsers: Chrome 110k, Firefox 300k, Edge 400k, IE11 150k). – oriadam Nov 26 '18 at 08:32
  • This is a very slow method, what if array would have thousands of elements? – Slava Fomin II Mar 22 '19 at 21:57
  • @SlavaFominII I extended the answer so it covers arrays with thousands of elements. – totymedli Mar 23 '19 at 03:13
73

If you're paranoid like me about using Math.max.apply (which could cause errors when given large arrays according to MDN), try this:

function arrayMax(array) {
  return array.reduce(function(a, b) {
    return Math.max(a, b);
  });
}

function arrayMin(array) {
  return array.reduce(function(a, b) {
    return Math.min(a, b);
  });
}

Or, in ES6:

function arrayMax(array) {
  return array.reduce((a, b) => Math.max(a, b));
}

function arrayMin(array) {
  return array.reduce((a, b) => Math.min(a, b));
}

The anonymous functions are unfortunately necessary (instead of using Math.max.bind(Math) because reduce doesn't just pass a and b to its function, but also i and a reference to the array itself, so we have to ensure we don't try to call max on those as well.

Daniel Buckmaster
  • 7,108
  • 6
  • 39
  • 57
  • Your ES6 example, is there any reason why not just return `Math.max(...array)`? – Wojciech Bednarski Jul 20 '16 at 23:48
  • @WojciechBednarski [this page](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator#A_better_apply) seems to suggest that using the spread operator is the same as passing an array to `apply`, and therefore has the same downsides (maximum argument limit). – Daniel Buckmaster Jul 21 '16 at 01:07
  • Thanks for this. Just you can correct missing bracket after reduce: `function arrayMax(array) { return array.reduce(function(a, b) { return Math.max(a, b); }); // <--------- missing ) }` – Arkowsky Sep 28 '17 at 11:17
  • @DanielBuckmaster you can simplify it like this: `array.reduce(Math.min)`. Additionally I would add an initial value for the cases that the array length is 0 or 1: `array.reduce(Math.min, defaultValue)`. – Daniel Dietrich Nov 04 '17 at 13:41
  • **Update:** Sorry, I just recognized that Math.min takes a variable amount of arguments. My suggestion above does **not** work. – Daniel Dietrich Nov 04 '17 at 14:21
  • 1
    @DanielDietrich I guess doing the equivalent, calling `Math.min()` with no values, returns `Infinity`, so these functions could use `reduce(..., Infinity)` to match that behaviour. I prefer it to throw an exception though (as it does currently), because taking the minimum of an empty array seems likely to be an error. – Daniel Buckmaster Nov 05 '17 at 07:50
  • 1
    so far reduce is the slowest. – Алексей Лещук Apr 19 '18 at 07:24
62

Alternative Methods


The Math.min and Math.max are great methods to get the minimum and maximum item out of a collection of items, however it's important to be aware of some cavities that can comes with it.

Using them with an array that contains large number of items (more than ~10⁷ items, depends on the user's browser) most likely will crash and give the following error message:

const arr = Array.from(Array(1000000).keys());
Math.min(arr);
Math.max(arr);

Uncaught RangeError: Maximum call stack size exceeded

UPDATE
Latest browsers might return NaN instead. That might be a better way to handle errors, however it doesn't solve the problem just yet.

Instead, consider using something like so:

function maxValue(arr) {
  return arr.reduce((max, val) => max > val ? max : val)
}

Or with better run-time:

function maxValue(arr) {
  let max = arr[0];

  for (let val of arr) {
    if (val > max) {
      max = val;
    }
  }
  return max;
}

Or to get both Min and Max:

function getMinMax(arr) {
  return arr.reduce(({min, max}, v) => ({
    min: min < v ? min : v,
    max: max > v ? max : v,
  }), { min: arr[0], max: arr[0] });
}

Or with even better run-time*:

function getMinMax(arr) {
  let min = arr[0];
  let max = arr[0];
  let i = arr.length;
    
  while (i--) {
    min = arr[i] < min ? arr[i] : min;
    max = arr[i] > max ? arr[i] : max;
  }
  return { min, max };
}

* Tested with 1,000,000 items:
Just for a reference, the 1st function run-time (on my machine) was 15.84ms vs 2nd function with only 4.32ms.

Lior Elrom
  • 19,660
  • 16
  • 80
  • 92
  • 2
    Just spread the array. `Math.min(...arr)`. – Ricardo Nolde Jun 21 '21 at 22:35
  • @RicardoNolde Unfortunately spreading the array doesn't change the way that the Math.min/max functions works (Tested on Chrome v91). If that works for you, please share which browser/version you use. – Lior Elrom Jun 22 '21 at 14:37
  • 1
    Sorry, I should have been more clear. The `NaN` problem happens because you're passing a straight array. In the browsers I have tested, it always returns `NaN`; that can be solved by spreading the array. The other issue you've raised -- the maximum call stack size -- still applies, regardless of spread. – Ricardo Nolde Jun 24 '21 at 00:12
45

Two ways are shorter and easy:

let arr = [2, 6, 1, 0]

Way 1:

let max = Math.max.apply(null, arr)

Way 2:

let max = arr.reduce(function(a, b) {
    return Math.max(a, b);
});
Hafizur Rahman
  • 2,314
  • 21
  • 29
  • Watch out if the array is empty - you'll get negative infinity which may not be what you want. If you prefer to get `0` you can use `[0].concat(arr)` or with spread syntax `[0, ...arr]` (in place of 'arr') – Simon_Weaver Jan 04 '19 at 05:38
  • is there a way to exclude null values in Way 1? – bonbon.langes Jun 04 '20 at 08:23
  • 2
    @hafizur-rahman way #1 cannot deal with large numbers! (as #2 can). Try with any array that has more than ~10⁷ items - Array.from(Array(1000000).keys()) – Lior Elrom Feb 18 '21 at 21:10
42

.apply is often used when the intention is to invoke a variadic function with a list of argument values, e.g.

The Math.max([value1[,value2, ...]]) function returns the largest of zero or more numbers.

Math.max(10, 20); // 20
Math.max(-10, -20); // -10
Math.max(-10, 20); // 20

The Math.max() method doesn't allow you to pass in an array. If you have a list of values of which you need to get the largest, you would normally call this function using Function.prototype.apply(), e.g.

Math.max.apply(null, [10, 20]); // 20
Math.max.apply(null, [-10, -20]); // -10
Math.max.apply(null, [-10, 20]); // 20

However, as of the ECMAScript 6 you can use the spread operator:

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

Using the spread operator, the above can be rewritten as such:

Math.max(...[10, 20]); // 20
Math.max(...[-10, -20]); // -10
Math.max(...[-10, 20]); // 20

When calling a function using the variadic operator, you can even add additional values, e.g.

Math.max(...[10, 20], 50); // 50
Math.max(...[-10, -20], 50); // 50

Bonus:

Spread operator enables you to use the array literal syntax to create new arrays in situations where in ES5 you would need to fall back to imperative code, using a combination of push, splice, etc.

let foo = ['b', 'c'];
let bar = ['a', ...foo, 'd', 'e']; // ['a', 'b', 'c', 'd', 'e']
Gajus
  • 69,002
  • 70
  • 275
  • 438
24

You do it by extending the Array type:

Array.max = function( array ){
    return Math.max.apply( Math, array );
};
Array.min = function( array ){
    return Math.min.apply( Math, array );
}; 

Boosted from here (by John Resig)

brettkelly
  • 27,655
  • 8
  • 56
  • 72
22

A simple solution to find the minimum value over an Array of elements is to use the Array prototype function reduce:

A = [4,3,-9,-2,2,1];
A.reduce((min, val) => val < min ? val : min, A[0]); // returns -9

or using JavaScript's built-in Math.Min() function (thanks @Tenflex):

A.reduce((min,val) => Math.min(min,val), A[0]);

This sets min to A[0], and then checks for A[1]...A[n] whether it is strictly less than the current min. If A[i] < min then min is updated to A[i]. When all array elements has been processed, min is returned as the result.

EDIT: Include position of minimum value:

A = [4,3,-9,-2,2,1];
A.reduce((min, val) => val < min._min ? {_min: val, _idx: min._curr, _curr: min._curr + 1} : {_min: min._min, _idx: min._idx, _curr: min._curr + 1}, {_min: A[0], _idx: 0, _curr: 0}); // returns { _min: -9, _idx: 2, _curr: 6 }
Nicolas Lykke Iversen
  • 3,660
  • 1
  • 11
  • 9
18

For a concise, modern solution, one can perform a reduce operation over the array, keeping track of the current minimum and maximum values, so the array is only iterated over once (which is optimal). Destructuring assignment is used here for succinctness.

let array = [100, 0, 50];
let [min, max] = array.reduce(([prevMin,prevMax], curr)=>
   [Math.min(prevMin, curr), Math.max(prevMax, curr)], [Infinity, -Infinity]);
console.log("Min:", min);
console.log("Max:", max);

To only find either the minimum or maximum, we can use perform a reduce operation in much the same way, but we only need to keep track of the previous optimal value. This method is better than using apply as it will not cause errors when the array is too large for the stack.

const arr = [-1, 9, 3, -6, 35];

//Only find minimum
const min = arr.reduce((a,b)=>Math.min(a,b), Infinity);
console.log("Min:", min);//-6

//Only find maximum
const max = arr.reduce((a,b)=>Math.max(a,b), -Infinity);
console.log("Max:", max);//35
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
16

One more way to do it:

var arrayMax = Function.prototype.apply.bind(Math.max, null);

Usage:

var max = arrayMax([2, 5, 1]);
gion_13
  • 41,171
  • 10
  • 96
  • 108
sbr
  • 4,735
  • 5
  • 43
  • 49
  • Can someone explain how this works? This is pretty dope. Is my understanding correct: arrayMax is a function and we bind something to a property of its prototype? What is this apply.bind and does every prototype have it? – Sam Sep 26 '13 at 17:39
  • You may check out: http://benalman.com/news/2012/09/partial-application-in-javascript/ – sbr Oct 12 '13 at 04:25
16

Others have already given some solutions in which they augment Array.prototype. All I want in this answer is to clarify whether it should be Math.min.apply( Math, array ) or Math.min.apply( null, array ). So what context should be used, Math or null?

When passing null as a context to apply, then the context will default to the global object (the window object in the case of browsers). Passing the Math object as the context would be the correct solution, but it won't hurt passing null either. Here's an example when null might cause trouble, when decorating the Math.max function:

// decorate Math.max
(function (oldMax) {
    Math.max = function () {
        this.foo(); // call Math.foo, or at least that's what we want

        return oldMax.apply(this, arguments);
    };
})(Math.max);

Math.foo = function () {
    print("foo");
};

Array.prototype.max = function() {
  return Math.max.apply(null, this); // <-- passing null as the context
};

var max = [1, 2, 3].max();

print(max);

The above will throw an exception because this.foo will be evaluated as window.foo, which is undefined. If we replace null with Math, things will work as expected and the string "foo" will be printed to the screen (I tested this using Mozilla Rhino).

You can pretty much assume that nobody has decorated Math.max so, passing null will work without problems.

Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
  • 3
    Point taken. However why would someone decorate `Foo.staticMethod` and reference `this`? Would that not be a mistake in the design of the decorator? (unless of course they were *wanting* to reference the global scope, and *want* to remain independent of the JavaScript engine being used, eg Rhino). – Roatin Marth Nov 03 '09 at 18:57
  • 2
    [The spec](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) is explicit about which specced functions should refer to "the **this** value" (indeed, that phrase appears 125 times in the specification). `Math.max`, implemented per spec, does not use `this`. If somebody overrides `Math.max` such that it does use `this`, then they have made its behaviour violate spec and you should throw sharp objects at them. You should not code around that possibility any more than you would code around the possibility that somebody has swapped `Math.max` and `Math.min` for the lulz. – Mark Amery Feb 14 '15 at 17:59
15

I am surprised not one mentiond the reduce function.

var arr = [1, 10, 5, 11, 2]

var b = arr.reduce(function(previous,current){ 
                      return previous > current ? previous:current
                   });

b => 11
arr => [1, 10, 5, 11, 2]
Stallion_V
  • 71
  • 2
  • 6
14

This may suit your purposes.

Array.prototype.min = function(comparer) {

    if (this.length === 0) return null;
    if (this.length === 1) return this[0];

    comparer = (comparer || Math.min);

    var v = this[0];
    for (var i = 1; i < this.length; i++) {
        v = comparer(this[i], v);    
    }

    return v;
}

Array.prototype.max = function(comparer) {

    if (this.length === 0) return null;
    if (this.length === 1) return this[0];

    comparer = (comparer || Math.max);

    var v = this[0];
    for (var i = 1; i < this.length; i++) {
        v = comparer(this[i], v);    
    }

    return v;
}
ChaosPandion
  • 77,506
  • 18
  • 119
  • 157
  • you should initialize your v with 'this[0]' in case no numbers are smaller than 0 – jasonmw Nov 03 '09 at 18:28
  • Is `comparer` supposed to be called in some specific scope? Because as is it references `this[index]` which is `undefined` everytime. – Roatin Marth Nov 03 '09 at 18:50
  • Fixed, I always forget about function level scoping. – ChaosPandion Nov 03 '09 at 18:54
  • Oh now, now @Ionut G. Stan will critique you for the same "wrong context" argument as he did me, since your default comparer (`Math.xxx`) will be running in the global scope... – Roatin Marth Nov 03 '09 at 19:00
  • That may be true, but the new function signature requires no scope as it takes the 2 objects that needs to be compared. – ChaosPandion Nov 03 '09 at 19:04
14

https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Math/max

function getMaxOfArray(numArray) {
  return Math.max.apply(null, numArray);
}

var arr = [100, 0, 50];
console.log(getMaxOfArray(arr))

this worked for me.

Ruslan López
  • 4,433
  • 2
  • 26
  • 37
Fuad Ibrahimov
  • 492
  • 2
  • 10
  • 21
12

I thought I'd share my simple and easy to understand solution.

For the min:

var arr = [3, 4, 12, 1, 0, 5];
var min = arr[0];
for (var k = 1; k < arr.length; k++) {
  if (arr[k] < min) {
    min = arr[k];
  }
}
console.log("Min is: " + min);

And for the max:

var arr = [3, 4, 12, 1, 0, 5];
var max = arr[0];
for (var k = 1; k < arr.length; k++) {
  if (arr[k] > max) {
    max = arr[k];
  }
}
console.log("Max is: " + max);
Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
12

let array = [267, 306, 108] let longest = Math.max(...array);

Trilok Singh
  • 1,227
  • 12
  • 10
  • 2
    This exact approach has already been mentioned in [totymedli’s answer](https://stackoverflow.com/a/30834687/4642212), [C.K’s answer](https://stackoverflow.com/a/55066646/4642212), [Abdennour TOUMI’s answer](https://stackoverflow.com/a/39106546/4642212), [shilovk’s answer](https://stackoverflow.com/a/37300098/4642212), not including all the deleted answers. Your (unformatted) answer adds nothing. – Sebastian Simon Oct 03 '20 at 15:20
10

Aside using the math function max and min, another function to use is the built in function of sort(): here we go

const nums = [12, 67, 58, 30].sort((x, y) => 
x -  y)
let min_val = nums[0]
let max_val = nums[nums.length -1]
black.swordsman
  • 111
  • 2
  • 9
Chukwuemeka Maduekwe
  • 6,687
  • 5
  • 44
  • 67
  • 2
    Hmm wouldn't `sort()` take O(n*log(n)) time whereas merely iterating through the array would take linear time? – mbil Dec 27 '21 at 23:39
10
array.sort((a, b) => b - a)[0];

Gives you the maximum value in an array of numbers.

array.sort((a, b) => a - b)[0];

Gives you the minimum value in an array of numbers.

let array = [0,20,45,85,41,5,7,85,90,111];

let maximum = array.sort((a, b) => b - a)[0];
let minimum = array.sort((a, b) => a - b)[0];

console.log(minimum, maximum)
Adam Beleko
  • 676
  • 7
  • 15
10

For an array containing objects instead of numbers:

arr = [
  { name: 'a', value: 5 },
  { name: 'b', value: 3 },
  { name: 'c', value: 4 }
]

You can use reduce to get the element with the smallest value (min)

arr.reduce((a, b) => a.value < b.value ? a : b)
// { name: 'b', value: 3 }

or the largest value (max)

arr.reduce((a, b) => a.value > b.value ? a : b)
// { name: 'a', value: 5 }
laktak
  • 57,064
  • 17
  • 134
  • 164
10

For big arrays (~10⁷ elements), Math.min and Math.max procuces a RangeError (Maximum call stack size exceeded) in node.js.

For big arrays, a quick & dirty solution is:

Array.prototype.min = function() {
    var r = this[0];
    this.forEach(function(v,i,a){if (v<r) r=v;});
    return r;
};
Peter
  • 5,138
  • 5
  • 29
  • 38
9

Iterate through, keeping track as you go.

var min = null;
var max = null;
for (var i = 0, len = arr.length; i < len; ++i)
{
    var elem = arr[i];
    if (min === null || min > elem) min = elem;
    if (max === null || max < elem) max = elem;
}
alert( "min = " + min + ", max = " + max );

This will leave min/max null if there are no elements in the array. Will set min and max in one pass if the array has any elements.

You could also extend Array with a range method using the above to allow reuse and improve on readability. See a working fiddle at http://jsfiddle.net/9C9fU/

Array.prototype.range = function() {

    var min = null,
        max = null,
        i, len;

    for (i = 0, len = this.length; i < len; ++i)
    {
        var elem = this[i];
        if (min === null || min > elem) min = elem;
        if (max === null || max < elem) max = elem;
    }

    return { min: min, max: max }
};

Used as

var arr = [3, 9, 22, -7, 44, 18, 7, 9, 15];

var range = arr.range();

console.log(range.min);
console.log(range.max);
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • @JordanDillonChapian I'd agree, but it would be trivial to extend this to a `range` function that would be the best way to get both the min and max at the same time IMO - as I've done with an update to my answer. – tvanfosson Jul 13 '14 at 14:25
9

I had the same problem, I needed to obtain the minimum and maximum values of an array and, to my surprise, there were no built-in functions for arrays. After reading a lot, I decided to test the "top 3" solutions myself:

  1. discrete solution: a FOR loop to check every element of the array against the current max and/or min value;
  2. APPLY solution: sending the array to the Math.max and/or Math.min internal functions using apply(null,array);
  3. REDUCE solution: recursing a check against every element of the array using reduce(function).

The test code was this:

function GetMaxDISCRETE(A)
{   var MaxX=A[0];

    for (var X=0;X<A.length;X++)
        if (MaxX<A[X])
            MaxX=A[X];

    return MaxX;
}

function GetMaxAPPLY(A)
{   return Math.max.apply(null,A);
}

function GetMaxREDUCE(A)
{   return A.reduce(function(p,c)
    {   return p>c?p:c;
    });
}

The array A was filled with 100,000 random integer numbers, each function was executed 10,000 times on Mozilla Firefox 28.0 on an intel Pentium 4 2.99GHz desktop with Windows Vista. The times are in seconds, retrieved by performance.now() function. The results were these, with 3 fractional digits and standard deviation:

  1. Discrete solution: mean=0.161s, sd=0.078
  2. APPLY solution: mean=3.571s, sd=0.487
  3. REDUCE solution: mean=0.350s, sd=0.044

The REDUCE solution was 117% slower than the discrete solution. The APPLY solution was the worse, 2,118% slower than the discrete solution. Besides, as Peter observed, it doesn't work for large arrays (about more than 1,000,000 elements).

Also, to complete the tests, I tested this extended discrete code:

var MaxX=A[0],MinX=A[0];

for (var X=0;X<A.length;X++)
{   if (MaxX<A[X])
        MaxX=A[X];
    if (MinX>A[X])
        MinX=A[X];
}

The timing: mean=0.218s, sd=0.094

So, it is 35% slower than the simple discrete solution, but it retrieves both the maximum and the minimum values at once (any other solution would take at least twice that to retrieve them). Once the OP needed both values, the discrete solution would be the best choice (even as two separate functions, one for calculating maximum and another for calculating minimum, they would outperform the second best, the REDUCE solution).

Cyberknight
  • 156
  • 2
  • 6
9

You can use the following function anywhere in your project:

function getMin(array){
    return Math.min.apply(Math,array);
}

function getMax(array){
    return Math.max.apply(Math,array);
}

And then you can call the functions passing the array:

var myArray = [1,2,3,4,5,6,7];
var maximo = getMax(myArray); //return the highest number
falsarella
  • 12,217
  • 9
  • 69
  • 115
Max Cabrera
  • 121
  • 1
  • 6
9

The following code works for me :

var valueList = [10,4,17,9,3];
var maxValue = valueList.reduce(function(a, b) { return Math.max(a, b); });
var minValue = valueList.reduce(function(a, b) { return Math.min(a, b); });
Gogol
  • 3,033
  • 4
  • 28
  • 57
jaydip jadhav
  • 477
  • 4
  • 5
9

let arr=[20,8,29,76,7,21,9]
Math.max.apply( Math, arr ); // 76

Shashwat Gupta
  • 5,071
  • 41
  • 33
5

Here's one way to get the max value from an array of objects. Create a copy (with slice), then sort the copy in descending order and grab the first item.

var myArray = [
    {"ID": 1, "Cost": 200},
    {"ID": 2, "Cost": 1000},
    {"ID": 3, "Cost": 50},
    {"ID": 4, "Cost": 500}
]

maxsort = myArray.slice(0).sort(function(a, b) { return b.ID - a.ID })[0].ID; 
falsarella
  • 12,217
  • 9
  • 69
  • 115
Ben
  • 584
  • 9
  • 8
5

Simple stuff, really.

var arr = [10,20,30,40];
arr.max = function() { return  Math.max.apply(Math, this); }; //attach max funct
arr.min = function() { return  Math.min.apply(Math, this); }; //attach min funct

alert("min: " + arr.min() + " max: " + arr.max());
falsarella
  • 12,217
  • 9
  • 69
  • 115
Brian
  • 3,653
  • 1
  • 22
  • 33
5

Using Math.max() or Math.min()

Math.max(10, 20);   //  20
Math.min(-10, -20); // -20

The following function uses Function.prototype.apply() to find the maximum element in a numeric array. getMaxOfArray([1, 2, 3]) is equivalent to Math.max(1, 2, 3), but you can use getMaxOfArray() on programmatically constructed arrays of any size.

function getMaxOfArray(numArray) {
  return Math.max.apply(null, numArray);
}

Or with the new spread operator, getting the maximum of an array becomes a lot easier.

var arr = [1, 2, 3];
var max = Math.max(...arr); // 3
var min = Math.min(...arr); // 1
shilovk
  • 11,718
  • 17
  • 75
  • 74
5

You can use lodash's methods

_.max([4, 2, 8, 6]);
returns => 8

https://lodash.com/docs/4.17.15#max

_.min([4, 2, 8, 6]);
returns => 2

https://lodash.com/docs/4.17.15#min

Esin ÖNER
  • 1,046
  • 11
  • 9
  • 2
    This solution works with large arrays. Does not give the error `Maximum call stack size exceeded` – Nyxynyx Feb 25 '20 at 04:22
4

ChaosPandion's solution works if you're using protoype. If not, consider this:

Array.max = function( array ){
    return Math.max.apply( Math, array );
};

Array.min = function( array ){
    return Math.min.apply( Math, array );
};

The above will return NaN if an array value is not an integer so you should build some functionality to avoid that. Otherwise this will work.

jay
  • 10,275
  • 5
  • 34
  • 52
4

If you use the library sugar.js, you can write arr.min() and arr.max() as you suggest. You can also get min and max values from non-numeric arrays.

min( map , all = false ) Returns the element in the array with the lowest value. map may be a function mapping the value to be checked or a string acting as a shortcut. If all is true, will return all min values in an array.

max( map , all = false ) Returns the element in the array with the greatest value. map may be a function mapping the value to be checked or a string acting as a shortcut. If all is true, will return all max values in an array.

Examples:

[1,2,3].min() == 1
['fee','fo','fum'].min('length') == "fo"
['fee','fo','fum'].min('length', true) == ["fo"]
['fee','fo','fum'].min(function(n) { return n.length; }); == "fo"
[{a:3,a:2}].min(function(n) { return n['a']; }) == {"a":2}
['fee','fo','fum'].max('length', true) == ["fee","fum"]

Libraries like Lo-Dash and underscore.js also provide similar powerful min and max functions:

Example from Lo-Dash:

_.max([4, 2, 8, 6]) == 8
var characters = [
  { 'name': 'barney', 'age': 36 },
  { 'name': 'fred',   'age': 40 }
];
_.max(characters, function(chr) { return chr.age; }) == { 'name': 'fred', 'age': 40 }
Community
  • 1
  • 1
andersh
  • 8,105
  • 6
  • 39
  • 30
4

Try

let max= a=> a.reduce((m,x)=> m>x ? m:x);
let min= a=> a.reduce((m,x)=> m<x ? m:x);

let max= a=> a.reduce((m,x)=> m>x ? m:x);
let min= a=> a.reduce((m,x)=> m<x ? m:x);

// TEST - pixel buffer
let arr = Array(200*800*4).fill(0); 
arr.forEach((x,i)=> arr[i]=100-i%101); 

console.log('Max', max(arr));
console.log('Min', min(arr))

For Math.min/max (+apply) we get error:

Maximum call stack size exceeded (Chrome 74.0.3729.131)

// TEST - pixel buffer
let arr = Array(200*800*4).fill(0); 
arr.forEach((x,i)=> arr[i]=100-i%101); 

// Exception: Maximum call stack size exceeded

try {
  let max1= Math.max(...arr);          
} catch(e) { console.error('Math.max :', e.message) }

try {
  let max2= Math.max.apply(null, arr); 
} catch(e) { console.error('Math.max.apply :', e.message) }


// same for min
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
4

In this day and age (in 2022), the most efficient way to get min + max from an array is to do it in a single iteration, via reduce.

  • In JavaScript:
const arr = [3, 0, -2, 5, 9, 4];

const i = arr.reduce((p, c) => {
    p.min = c < p.min ? c : p.min ?? c;
    p.max = c > p.max ? c : p.max ?? c;
    return p;
}, {min: undefined, max: undefined});

console.log(i); //=> { min: -2, max: 9 }

And when the input has no data, it will output {min: undefined, max: undefined}.

In TypeScript, you would just add type casting, so the return type is inferred as {min: number | undefined, max: number | undefined}, and not as {min: any, max: any}:

const arr = [3, 0, -2, 5, 9, 4];

const i = arr.reduce((p, c) => {
    p.min = c < p.min! ? c : p.min ?? c;
    p.max = c > p.max! ? c : p.max ?? c;
    return p;
}, {min: undefined, max: undefined} as { min: number | undefined, max: number | undefined });

console.log(i); //=> { min: -2, max: 9 }

UPDATE

Following kiran goud comment, here's an alternative that uses arrays instead of objects:

const i = arr.reduce((p, c) => {
    p[0] = c < p[0] ? c : p[0] ?? c;
    p[1] = c > p[1] ? c : p[1] ?? c;
    return p;
}, [undefined, undefined]);

console.log(i); //=> [-2, 9]
vitaly-t
  • 24,279
  • 15
  • 116
  • 138
3
let arr = [2,5,3,5,6,7,1];

let max = Math.max(...arr); // 7
let min = Math.min(...arr); // 1
U.A
  • 2,991
  • 3
  • 24
  • 36
  • 6
    This solution has already been provided by multiple other answerers to this question. What does your answer add? – Nick Mar 09 '19 at 01:52
2
minHeight = Math.min.apply({},YourArray);
minKey    = getCertainKey(YourArray,minHeight);
maxHeight = Math.max.apply({},YourArray);
maxKey    = getCertainKey(YourArray,minHeight);
function getCertainKey(array,certainValue){
   for(var key in array){
      if (array[key]==certainValue)
         return key;
   }
} 
stevenlee
  • 31
  • 5
2

Here's a plain vanilla JS approach.

function getMinArrayVal(seq){
    var minVal = seq[0];
    for(var i = 0; i<seq.length-1; i++){
        if(minVal < seq[i+1]){
        continue;
        } else {
        minVal = seq[i+1];
        }
    }
    return minVal;
}
2

If you are using prototype.js framework, then this code will work ok:

arr.min();
arr.max();

Documented here: Javascript prototype framework for max

Krešimir Prcela
  • 4,257
  • 33
  • 46
1

create a simple object

var myArray = new Array();

myArray = [10,12,14,100];

var getMaxHeight = {
     hight : function( array ){ return Math.max.apply( Math, array );
}

getMaxHeight.hight(myArray);
falsarella
  • 12,217
  • 9
  • 69
  • 115
Yene Mulatu
  • 2,226
  • 1
  • 17
  • 13
  • 1
    why do you actually need an object for that? It's just a function that you're using in the end. And also, why are you defining your array twice? – gion_13 Sep 17 '13 at 05:57
  • The main solution here is not the array creation convention or assign value to a variable. You can use create array in any you want and assign value as you wish. – Yene Mulatu Sep 25 '13 at 19:49
  • I know it is not **the main solution**. In fact it isn't even part of the solution. If it were, maybe i'd down-voted you, but I didn't. I was just curious about why did you write the code that way. – gion_13 Sep 25 '13 at 20:08
1

You can use Array.sort but you'll have to write a simple number sorting function since the default is alphabetic.

Look at example 2 here.

Then you can grab arr[0] and arr[arr.length-1] to get min and max.

Pablo
  • 1,053
  • 9
  • 10
1

I like Linus's reduce() approach, especially for large arrays. But as long as you know you need both min and the max, why iterate over the array twice?

Array.prototype.minmax = function () {
  return this.reduce(function (p, v) {
    return [(p[0] < v ? p[0] : v), (p[1] > v ? p[1] : v)];
  }, [this[0], this[0]]);
}

Of course, if you prefer the iterative approach, you can do that too:

Array.prototype.minmax = function () {
    var mn = this[0], mx = this[0];
    this.forEach(function (v) {
        if (v < mn) mn = v;
        if (v > mx) mx = v;
    });
    return [mn, mx];
};
Community
  • 1
  • 1
fearless_fool
  • 33,645
  • 23
  • 135
  • 217
1

To prevent "max" and "min" to be listed in a "for ... in" loop:

Object.defineProperty(Array.prototype, "max", {
    enumerable: false,
    configurable: false,
    writable: false,    
    value: function() {
        return Math.max.apply(null, this);
    }
});
Object.defineProperty(Array.prototype, "min", {
    enumerable: false,
    configurable: false,
    writable: false,    
    value: function() {
        return Math.min.apply(null, this);
    }
});

Usage:

var x = [10,23,44,21,5];
x.max(); //44
x.min(); //5
lepe
  • 24,677
  • 9
  • 99
  • 108
1

Below script worked for me in ndoejs:

 var numbers = [1, 2, 3, 4];
 console.log('Value:: ' + Math.max.apply(null, numbers) ); // 4
Rahul Mankar
  • 910
  • 9
  • 17
1

well I would like to do this in the below way

const findMaxAndMin = (arr) => {
  if (arr.length <= 0) return -1;
  let min = arr[0];
  let max = arr[0];
  arr.forEach((n) => {
    n > max ? (max = n) : false;
    n < min ? (min = n) : false;
  });
  return [min, max];
};
Bhumit 070
  • 416
  • 4
  • 12
1

Another solution

   let arr = [1,10,25,15,31,5,7,101];
    let sortedArr = arr.sort((a, b) => a - b)

    let min = sortedArr[0];
    let max = sortedArr[arr.length-1]

    console.log(`min => ${min}. Max => ${max}`)

screenshot

Yusuf Ganiyu
  • 842
  • 9
  • 8
1

Finding the Max and Min elements of an array in JavaScript.

There are several approaches you can use:

Using Math.min() and Math.max()

let array = [100, 0, 50];
Math.min(...array); // 0
Math.max(...array); // 100

Using Sorting

let array = [100, 0, 50];
arraySorted = array.toSorted((a, b) => a - b); // [0, 50, 100];
arraySorted.at(0);  // 0
arraySorted.at(-1); // 100

Using simple for-loop

let array = [100, 0, 50];
let maxNumber = array[0];
let minNumber = array[0];
for (let i = 1; i < array.length; i++) {
  if (array[i] > maxNumber) {
    maxNumber = array[i];
  }
  if (array[i] < minNumber) {
    minNumber = array[i];
  }
}
XMehdi01
  • 5,538
  • 2
  • 10
  • 34
1

The best way!! make it easy :P, with Math.min(...array) and Math.max(...array) =Denter image description here

0

If you need performance then this is the best way for small arrays:

var min = 99999;
var max = 0;
for(var i = 0; i < v.length; i++)
{
    if(v[i] < min)
    {
        min = v[i];
    }
    if(v[i] >= max)
    {
        max = v[i];
    }
}
Kamil
  • 1,633
  • 2
  • 21
  • 24
0

Insert the numbers seperated by a comma and click on the event you want to call ie Get the Max or min number.

        function maximumNumber() {
       
            var numberValue = document.myForm.number.value.split(",");
            var numberArray = [];
    
            for (var i = 0, len = numberValue.length; i < len; i += 1) {
    
                numberArray.push(+numberValue[i]);
    
                var largestNumber = numberArray.reduce(function (x, y) {
                    return (x > y) ? x : y;
                });
            }
    
            document.getElementById("numberOutput").value = largestNumber;
    
        }
    
        function minimumNumber() {
  
            var numberValue = document.myForm.number.value.split(",");
            var numberArray = [];
    
            for (var i = 0, len = numberValue.length; i < len; i += 1) {
    
                numberArray.push(+numberValue[i]);
    
                var smallestNumber = numberArray.reduce(function (x, y) {
                    return (x < y) ? x : y;
                });
            }
    
            document.getElementById("numberOutput").value = smallestNumber;
    
        }
    
    
            function restrictCharacters(evt) {
    
                evt = (evt) ? evt : window.event;
                var charCode = (evt.which) ? evt.which : evt.keyCode;
                if (((charCode >= '48') && (charCode <= '57')) || (charCode == '44')) {
                    return true;
                }
                else {
                    return false;
                }
            }
    
    <div>    
            <form name="myForm">
            <table>
            <tr>
                <td>Insert Number</td>
               
                <td><input type="text" name="number" id="number" onkeypress="return restrictCharacters(event);" /></td>
                
                <td><input type="button" value="Maximum" onclick="maximumNumber();" /></td>
                
                <td><input type="button" value="Minimum" onclick="minimumNumber();"/></td>
                
                <td><input type="text" id="numberOutput" name="numberOutput" /></td>
    
            </tr>
            </table>
            </form>
        </div>
Mayur Narula
  • 150
  • 1
  • 4
0

if you have complex object, you could use sort....such as: if I want get item which contains MAX/MIN value of below objs.

var objs= [
{name:"Apple",value:3},
{name:"Love",value:32},
{name:"Cheese",value:1},
{name:"Pork",value:77},
{name:"Xmas",value:99}        
];

I will do a sort:

objs.sort(function(a, b){return a.value-b.value});

Then: objs[0] is the MIN, objs[objs.length-1] is the MAX.

Vin.X
  • 4,759
  • 3
  • 28
  • 35
  • the `sort` actually update the array, like mentionned in @Ben answer. OP is only about getting the min/max value. – Hacketo Dec 04 '15 at 12:49
  • you could make a copy of the current array sort it and get min/max. Few extra lines of code. However, i was just trying to post an alternative solution. lol. And the array i was working on has 3 levels of objects, i have to get min/max from the 2nd level. It was not just to get min/max from single valued array. – Vin.X Dec 05 '15 at 01:40
0

You may not want to add methods to the Array prototype, which may conflict with other libraries.

I've seen a lot of examples use forEach which, I wouldn't recommend for large arrays due to its poor performance vs a for loop. https://coderwall.com/p/kvzbpa/don-t-use-array-foreach-use-for-instead

Also Math.max(Math, [1,2,3]); Always gives me NaN?

function minArray(a) {
  var min=a[0]; for(var i=0,j=a.length;i<j;i++){min=a[i]<min?a[i]:min;}
  return min;
}

function maxArray(a) {
  var max=a[0]; for(var i=0,j=a.length;i<j;i++){max=a[i]>max?a[i]:max;}
  return max;
}

minArray([1,2,3]); // returns 1

If you have an array of objects the minArray() function example below will accept 2 parameters, the first is the array and the second is the key name for the object key value to compare. The function in this case would return the index of the array that has the smallest given key value.

function minArray(a, key) {
  var min, i, j, index=0;
  if(!key) {
    min=a[0]; 
    for(i=0,j=a.length;i<j;i++){min=a[i]<min?a[i]:min;}
    return min;
  }
  min=a[0][key];
  for(i=0,j=a.length;i<j;i++){
    if(a[i][key]<min) {
      min = a[i][key];
      index = i;
    }
  }
    return index;
}

var a = [{fee: 9}, {fee: 2}, {fee: 5}];

minArray(a, "fee"); // returns 1, as 1 is the proper array index for the 2nd array element.
micahblu
  • 4,924
  • 5
  • 27
  • 33
  • Why is this the top answer? The top one should be http://stackoverflow.com/a/1669222/390014 – draw Apr 08 '16 at 18:50
  • Yes I'd agree to use the Math.min.apply() for finding the minimum primitive array value, I recall seeing comments leaving out the apply call which gave me the null response which is why I came up with the first solution. Though my second solution should still hold merit for object arrays, of course unless there's a better one :) – micahblu Apr 09 '16 at 22:03
0

linear, almost-purely-functional-approach

var min=[0, 29, 25].map((function(max) {max=-Infinity; return function(e) {return max=Math.max(max, e);}})())[0]

More examples:

Finding out min value

function getMin(arr) {
    return (ar || [0, 29, 25]).
        map((function(max) {max=-Infinity; return function(e) {return max=Math.max(max, e);}})())[0];
}

or using Array.map method with variable closuring

function getMin(arrObjs) {
    return (arrObjs || [{val: 0}, {val: 29}, {val: 25}]).
        map((function(max) {max=-Infinity; return function(e) {return max=(max.val>e.val?max:e);}})())[0];
}

Finding out max value

function getMax(arr) {
    return (ar || [0, 29, 25]).
        map((function(v) {v=Infinity; return function(e) {return v=Math.min(v, e);}})())[0];
}

for array of objects

function getMax(arrObjs) {
    return (arrObjs || [{val: 0}, {val: 29}, {val: 25}]).
        map((function(v) {v=-Infinity; return function(e) {return v=(v.val<e.val?v:e);}})())[0];
}
test30
  • 3,496
  • 34
  • 26
0

A recursive solution to the problem

const findMinMax = (arr, max, min, i) => arr.length === i ? {
    min,
    max
  } :
  findMinMax(
    arr,
    arr[i] > max ? arr[i] : max,
    arr[i] < min ? arr[i] : min,
    ++i)

const arr = [5, 34, 2, 1, 6, 7, 9, 3];
const max = findMinMax(arr, arr[0], arr[1], 0)
console.log(max);
EugenSunic
  • 13,162
  • 13
  • 64
  • 86
0

Alternative Solns

class SmallestIntegerFinder {
  findSmallestInt(args) {
    return args.reduce((min,item)=>{ return (min<item ? min : item)});
  }
}

class SmallestIntegerFinder {
  findSmallestInt(args) {
    return Math.min(...args)
  }
}

class SmallestIntegerFinder {
  findSmallestInt(args) {
    return Math.min.apply(null, args);
  }
}

class SmallestIntegerFinder {
  findSmallestInt(args) {
    args.sort(function(a, b) {
    return a - b; } )
    return args[0];
  }
}
Papa Bravo
  • 31
  • 7
0

For learning purpose, you can do it by using variables and for loop without using built-in functions.

// Input sample data to the function
var arr = [-1, 0, 3, 100, 99, 2, 99];
// Just to show the result
console.log(findMinMax(arr));

function findMinMax(arr) {
  let arraySize = arr.length;
  if (arraySize > 0) {
    var MaxNumber = MinNumber = arr[0];
    for (var i = 0; i <= arraySize; i++) {
      if (arr[i] > MaxNumber) {
        MaxNumber = arr[i];
      }else if(arr[i] < MinNumber) {
        MinNumber = arr[i];
      }
    }
    var minMax = [MinNumber,MaxNumber];
    return minMax;
  } else {
    return 0;
  }
}
Mr-Faizan
  • 1,179
  • 1
  • 8
  • 9
0

To add to the many good answers here, here is a typescript version that can handle lists where some values are undefined.

How it can be used:

const testDates = [
  undefined,
  new Date('July 30, 1986'),
  new Date('July 31, 1986'),
  new Date('August 1, 1986'),
]
const max: Date|undefined = arrayMax(testDates); // Fri Aug 01 1986
const min: Date|undefined = arrayMin(testDates); // Min: Wed Jul 30 1986
const test: Date = arrayMin(testDates); // Static type error
const anotherTest: undefined = arrayMin(testDates); // Static type error

The definitions (the notEmpty definition is from this post):

function arrayMax<T>(values?: (T | null | undefined)[]): T | undefined {
    const nonEmptyValues = filterEmpty(values);
    if (nonEmptyValues.length === 0) {
        return undefined;
    }
    return nonEmptyValues.reduce((a, b) => (a >= b ? a : b), nonEmptyValues[0]);
}

function arrayMin<T>(values?: (T | null | undefined)[]): T | undefined {
    const nonEmptyValues = filterEmpty(values);
    if (nonEmptyValues.length === 0) {
        return undefined;
    }
    return nonEmptyValues.reduce((a, b) => (a <= b ? a : b), nonEmptyValues[0]);
}

function filterEmpty<T>(values?: (T | null | undefined)[] | null): T[] {
    return values?.filter(notEmpty) ?? [];
}

function notEmpty<T>(value: T | null | undefined): value is T {
    if (value === null || value === undefined) return false;
    const testDummy: T = value;
    return true;
}

I didn't use the Math.max function as suggested in the documentation because this way I can use this function with any comparable objects (if you know how to type this let me know so I can better define T).

cglacet
  • 8,873
  • 4
  • 45
  • 60
-1

Here is one more example. Calculate the Max/Min value from an array with lodash.

let array = [100, 0, 50];
var func = _.over(Math.max, Math.min);
var [max, min] = func(...array);
// => [100, 0]
console.log(max);
console.log(min);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
-9

I managed to solve my problem this way:

    var strDiv  = "4,8,5,1"
var arrayDivs   = strDiv.split(",")
var str = "";

for (i=0;i<arrayDivs.length;i++)
{
    if (i<arrayDivs.length-1)
    {
      str = str + eval('arrayDivs['+i+']')+',';
    } 
    else if (i==arrayDivs.length-1)
    {
      str = str + eval('arrayDivs['+i+']');
    }
}

str = 'Math.max(' + str + ')';
    var numMax = eval(str);

I hope I have helped.

Best regards.