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
141k31 gold badges172 silver badges209 bronze badges
answered Nov 3, 2009 at 18:23
Roatin MarthRoatin Marth
23.5k3 gold badges51 silver badges55 bronze badges
15
Using spread operator (ES6)
Math.max(...array) // The same with "min" => Math.min(...array)
Gass
6,9092 gold badges34 silver badges38 bronze badges
answered Aug 23, 2016 at 16:37
Abdennour TOUMIAbdennour TOUMI
85.5k38 gold badges243 silver badges251 bronze badges
9
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;
};
answered Nov 18, 2012 at 14:00
Linus UnnebäckLinus Unnebäck
22.6k14 gold badges73 silver badges89 bronze badges
6
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 toMath.max(1, 2, 3)
, but you can usegetMaxOfArray()
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
JSBen benchmark
JSBench.me benchmark
Benchmark source code
answered Jun 14, 2015 at 21:22
totymedlitotymedli
29k22 gold badges130 silver badges163 bronze badges
4
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.
answered Jul 27, 2015 at 1:00
7
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.
answered Oct 2, 2018 at 17:34
Lior ElromLior Elrom
19.4k16 gold badges80 silver badges92 bronze badges
3
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);
});
answered May 18, 2018 at 1:37
3
.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']
answered Dec 18, 2014 at 1:38
GajusGajus
67.9k70 gold badges271 silver badges436 bronze badges
1
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)
answered Nov 3, 2009 at 18:35
brettkellybrettkelly
27.6k8 gold badges56 silver badges71 bronze badges
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 }
answered Oct 29, 2017 at 11:26
2
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
answered Aug 20, 2020 at 22:47
UnmitigatedUnmitigated
70.6k8 gold badges58 silver badges77 bronze badges
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.
answered Nov 3, 2009 at 18:39
Ionuț G. StanIonuț G. Stan
175k18 gold badges188 silver badges202 bronze badges
2
One more way to do it:
var arrayMax = Function.prototype.apply.bind(Math.max, null);
Usage:
var max = arrayMax([2, 5, 1]);
gion_13
41k10 gold badges95 silver badges107 bronze badges
answered Sep 26, 2012 at 18:43
sbrsbr
4,6955 gold badges42 silver badges48 bronze badges
2
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]
2
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;
}
answered Nov 3, 2009 at 18:21
ChaosPandionChaosPandion
77.2k18 gold badges118 silver badges156 bronze badges
5
let array = [267, 306, 108]
let longest = Math.max(…array);
answered Oct 3, 2020 at 15:10
Trilok SinghTrilok Singh
1,17712 silver badges9 bronze badges
1
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);
answered Oct 13, 2016 at 16:37
Ionut NeculaIonut Necula
11k4 gold badges45 silver badges69 bronze badges
9
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;
};
answered Jan 24, 2012 at 12:43
PeterPeter
5,1085 gold badges29 silver badges38 bronze badges
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)
answered Jun 20, 2020 at 20:33
Adam BelekoAdam Beleko
6387 silver badges15 bronze badges
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 }
answered Aug 6, 2020 at 12:17
laktaklaktak
56.3k17 gold badges134 silver badges164 bronze badges
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]
answered Feb 14, 2020 at 15:29
1
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:
- discrete solution: a FOR loop to check every element of the array against the current max and/or min value;
- APPLY solution: sending the array to the Math.max and/or Math.min internal functions using apply(null,array);
- 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:
- Discrete solution: mean=0.161s, sd=0.078
- APPLY solution: mean=3.571s, sd=0.487
- 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).
answered Apr 2, 2014 at 17:46
CyberknightCyberknight
1562 silver badges6 bronze badges
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);
answered Nov 3, 2009 at 18:23
tvanfossontvanfosson
523k99 gold badges697 silver badges794 bronze badges
1
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.2k9 gold badges69 silver badges115 bronze badges
answered Aug 26, 2014 at 16:57
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,0334 gold badges28 silver badges57 bronze badges
answered May 26, 2017 at 12:40
0
let arr=[20,8,29,76,7,21,9]
Math.max.apply( Math, arr ); // 76
answered Oct 28, 2020 at 21:53
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.2k9 gold badges69 silver badges115 bronze badges
answered Sep 23, 2014 at 7:48
BrianBrian
3,6531 gold badge22 silver badges33 bronze badges
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.2k9 gold badges69 silver badges115 bronze badges
answered Jan 9, 2014 at 18:46
BenBen
5849 silver badges8 bronze badges
I have a simple JavaScript Array object containing a few numbers.
[267, 306, 108]
Is there a function that would find the largest number in this array?
Shog9
156k34 gold badges229 silver badges234 bronze badges
asked Sep 4, 2009 at 14:17
1
You can use the apply function, to call Math.max:
var array = [267, 306, 108];
var largest = Math.max.apply(Math, array); // 306
How does it work?
The apply function is used to call another function, with a given context and arguments, provided as an array. The min and max functions can take an arbitrary number of input arguments: Math.max(val1, val2, …, valN)
So if we call:
Math.min.apply(Math, [1, 2, 3, 4]);
The apply function will execute:
Math.min(1, 2, 3, 4);
Note that the first parameter, the context, is not important for these functions since they are static. They will work regardless of what is passed as the context.
answered Sep 4, 2009 at 14:19
3
The easiest syntax, with the new spread operator:
var arr = [1, 2, 3];
var max = Math.max(...arr);
Source : Mozilla MDN
answered Nov 3, 2015 at 12:16
A.IA.I
1,4382 gold badges15 silver badges18 bronze badges
3
I’m not a JavaScript expert, but I wanted to see how these methods stack up, so this was good practice for me. I don’t know if this is technically the right way to performance test these, but I just ran them one right after another, as you can see in my code.
Sorting and getting the 0th value is by far the worst method (and it modifies the order of your array, which may not be desirable). For the others, the difference is negligible unless you’re talking millions of indices.
Average results of five runs with a 100,000-index array of random numbers:
- reduce took 4.0392 ms to run
- Math.max.apply took 3.3742 ms to run
- sorting and getting the 0th value took 67.4724 ms to run
- Math.max within reduce() took 6.5804 ms to run
- custom findmax function took 1.6102 ms to run
var performance = window.performance
function findmax(array)
{
var max = 0,
a = array.length,
counter
for (counter=0; counter<a; counter++)
{
if (array[counter] > max)
{
max = array[counter]
}
}
return max
}
function findBiggestNumber(num) {
var counts = []
var i
for (i = 0; i < num; i++) {
counts.push(Math.random())
}
var a, b
a = performance.now()
var biggest = counts.reduce(function(highest, count) {
return highest > count ? highest : count
}, 0)
b = performance.now()
console.log('reduce took ' + (b - a) + ' ms to run')
a = performance.now()
var biggest2 = Math.max.apply(Math, counts)
b = performance.now()
console.log('Math.max.apply took ' + (b - a) + ' ms to run')
a = performance.now()
var biggest3 = counts.sort(function(a,b) {return b-a;})[0]
b = performance.now()
console.log('sorting and getting the 0th value took ' + (b - a) + ' ms to run')
a = performance.now()
var biggest4 = counts.reduce(function(highest, count) {
return Math.max(highest, count)
}, 0)
b = performance.now()
console.log('Math.max within reduce() took ' + (b - a) + ' ms to run')
a = performance.now()
var biggest5 = findmax(counts)
b = performance.now()
console.log('custom findmax function took ' + (b - a) + ' ms to run')
console.log(biggest + '-' + biggest2 + '-' + biggest3 + '-' + biggest4 + '-' + biggest5)
}
findBiggestNumber(1E5)
answered May 19, 2015 at 19:15
redOctober13redOctober13
3,6436 gold badges34 silver badges61 bronze badges
2
I’ve found that for bigger arrays (~100k elements), it actually pays to simply iterate the array with a humble for
loop, performing ~30% better than Math.max.apply()
:
function mymax(a)
{
var m = -Infinity, i = 0, n = a.length;
for (; i != n; ++i) {
if (a[i] > m) {
m = a[i];
}
}
return m;
}
Benchmark results
answered Dec 10, 2012 at 2:57
Ja͢ckJa͢ck
170k38 gold badges263 silver badges309 bronze badges
1
You could sort the array in descending order and get the first item:
[267, 306, 108].sort(function(a,b){return b-a;})[0]
answered Sep 4, 2009 at 14:20
GumboGumbo
640k108 gold badges774 silver badges843 bronze badges
8
Use:
var arr = [1, 2, 3, 4];
var largest = arr.reduce(function(x,y) {
return (x > y) ? x : y;
});
console.log(largest);
answered May 5, 2015 at 18:47
brroshanbrroshan
1,64017 silver badges19 bronze badges
2
Use Array.reduce:
[0,1,2,3,4].reduce(function(previousValue, currentValue){
return Math.max(previousValue,currentValue);
});
answered Apr 10, 2014 at 15:11
CodeToadCodeToad
4,6466 gold badges41 silver badges53 bronze badges
3
Finding max and min value the easy and manual way. This code is much faster than Math.max.apply
; I have tried up to 1000k numbers in array.
function findmax(array)
{
var max = 0;
var a = array.length;
for (counter=0;counter<a;counter++)
{
if (array[counter] > max)
{
max = array[counter];
}
}
return max;
}
function findmin(array)
{
var min = array[0];
var a = array.length;
for (counter=0;counter<a;counter++)
{
if (array[counter] < min)
{
min = array[counter];
}
}
return min;
}
mgthomas99
5,1443 gold badges18 silver badges21 bronze badges
answered Nov 26, 2013 at 10:37
1
Simple one liner
[].sort().pop()
answered Oct 7, 2019 at 9:45
YasirAzgarYasirAzgar
1,35516 silver badges15 bronze badges
Almost all of the answers use Math.max.apply()
which is nice and dandy, but it has limitations.
Function arguments are placed onto the stack which has a downside — a limit. So if your array is bigger than the limit it will fail with RangeError: Maximum call stack size exceeded.
To find a call stack size I used this code:
var ar = [];
for (var i = 1; i < 100*99999; i++) {
ar.push(1);
try {
var max = Math.max.apply(Math, ar);
} catch(e) {
console.log('Limit reached: '+i+' error is: '+e);
break;
}
}
It proved to be biggest on Firefox on my machine — 591519. This means that if you array contains more than 591519 items, Math.max.apply()
will result in RangeError.
The best solution for this problem is iterative way (credit: https://developer.mozilla.org/):
max = -Infinity, min = +Infinity;
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] > max)
max = numbers[i];
if (numbers[i] < min)
min = numbers[i];
}
I have written about this question on my blog here.
answered Oct 3, 2013 at 19:22
lukas.pukenislukas.pukenis
12.9k12 gold badges47 silver badges81 bronze badges
2
Yes, of course there exists Math.max.apply(null,[23,45,67,-45])
and the result is to return 67
.
answered Feb 1, 2015 at 15:34
Don’t forget that the wrap can be done with Function.prototype.bind
, giving you an «all-native» function.
var aMax = Math.max.apply.bind(Math.max, Math);
aMax([1, 2, 3, 4, 5]); // 5
answered Oct 11, 2013 at 1:37
Paul S.Paul S.
64.4k9 gold badges120 silver badges138 bronze badges
You could also extend Array
to have this function and make it part of every array.
Array.prototype.max = function(){return Math.max.apply( Math, this )};
myArray = [1,2,3];
console.log( myArray.max() );
dee-see
23.5k5 gold badges58 silver badges91 bronze badges
answered Jul 26, 2014 at 18:21
3
You can also use forEach:
var maximum = Number.MIN_SAFE_INTEGER;
var array = [-3, -2, 217, 9, -8, 46];
array.forEach(function(value){
if(value > maximum) {
maximum = value;
}
});
console.log(maximum); // 217
answered Sep 30, 2016 at 13:57
Benny CodeBenny Code
50.7k28 gold badges230 silver badges198 bronze badges
Using — Array.prototype.reduce()
is cool!
[267, 306, 108].reduce((acc,val)=> (acc>val)?acc:val)
where acc = accumulator and val = current value;
var a = [267, 306, 108].reduce((acc,val)=> (acc>val)?acc:val);
console.log(a);
answered Apr 12, 2017 at 6:02
aroraarora
8597 silver badges12 bronze badges
A recursive approach on how to do it using ternary operators
const findMax = (arr, max, i) => arr.length === i ? max :
findMax(arr, arr[i] > max ? arr[i] : max, ++i)
const arr = [5, 34, 2, 1, 6, 7, 9, 3];
const max = findMax(arr, arr[0], 0)
console.log(max);
answered Oct 2, 2019 at 22:06
EugenSunicEugenSunic
13.1k11 gold badges64 silver badges84 bronze badges
You can try this,
var arr = [267, 306, 108];
var largestNum = 0;
for(i=0; i<arr.length; i++) {
if(arr[i] > largest){
var largest = arr[i];
}
}
console.log(largest);
answered Jun 7, 2017 at 11:08
Aasha joneyAasha joney
5085 silver badges23 bronze badges
I just started with JavaScript, but I think this method would be good:
var array = [34, 23, 57, 983, 198];
var score = 0;
for(var i = 0; i = array.length; i++) {
if(array[ i ] > score) {
score = array[i];
}
}
answered Jul 5, 2017 at 11:54
Jakub KarkiJakub Karki
731 gold badge2 silver badges6 bronze badges
1
var nums = [1,4,5,3,1,4,7,8,6,2,1,4];
nums.sort();
nums.reverse();
alert(nums[0]);
Simplest Way:
var nums = [1,4,5,3,1,4,7,8,6,2,1,4]; nums.sort(); nums.reverse(); alert(nums[0]);
answered Nov 3, 2020 at 6:44
Run this:
Array.prototype.max = function(){
return Math.max.apply( Math, this );
};
And now try [3,10,2].max()
returns 10
answered May 17, 2017 at 12:32
RegarBoyRegarBoy
3,1681 gold badge21 silver badges44 bronze badges
Find Max and Min value using Bubble Sort
var arr = [267, 306, 108];
for(i=0, k=0; i<arr.length; i++) {
for(j=0; j<i; j++) {
if(arr[i]>arr[j]) {
k = arr[i];
arr[i] = arr[j];
arr[j] = k;
}
}
}
console.log('largest Number: '+ arr[0]);
console.log('Smallest Number: '+ arr[arr.length-1]);
answered Jul 11, 2018 at 6:23
ManojManoj
1,9282 gold badges15 silver badges20 bronze badges
1
Try this
function largestNum(arr) {
var currentLongest = arr[0]
for (var i=0; i< arr.length; i++){
if (arr[i] > currentLongest){
currentLongest = arr[i]
}
}
return currentLongest
}
answered Dec 27, 2018 at 11:37
ToufiqToufiq
1,07612 silver badges16 bronze badges
1
As per @Quasimondo’s comment, which seems to have been largely missed, the below seems to have the best performance as shown here: https://jsperf.com/finding-maximum-element-in-an-array. Note that while for the array in the question, performance may not have a significant effect, for large arrays performance becomes more important, and again as noted using Math.max()
doesn’t even work if the array length is more than 65535. See also this answer.
function largestNum(arr) {
var d = data;
var m = d[d.length - 1];
for (var i = d.length - 1; --i > -1;) {
if (d[i] > m) m = d[i];
}
return m;
}
answered Mar 4, 2019 at 9:16
James RayJames Ray
4043 silver badges15 bronze badges
One for/of
loop solution:
const numbers = [2, 4, 6, 8, 80, 56, 10];
const findMax = (...numbers) => {
let currentMax = numbers[0]; // 2
for (const number of numbers) {
if (number > currentMax) {
console.log(number, currentMax);
currentMax = number;
}
}
console.log('Largest ', currentMax);
return currentMax;
};
findMax(...numbers);
answered Apr 15, 2020 at 20:44
Mile MijatovićMile Mijatović
2,8322 gold badges22 silver badges41 bronze badges
Find the largest number in a multidimensional array
var max = [];
for(var i=0; arr.length>i; i++ ) {
var arra = arr[i];
var largest = Math.max.apply(Math, arra);
max.push(largest);
}
return max;
answered Aug 11, 2015 at 8:00
4
My solution to return largest numbers in arrays.
const largestOfFour = arr => {
let arr2 = [];
arr.map(e => {
let numStart = -Infinity;
e.forEach(num => {
if (num > numStart) {
numStart = num;
}
})
arr2.push(numStart);
})
return arr2;
}
answered Aug 2, 2020 at 11:14
Should be quite simple:
var countArray = [1,2,3,4,5,1,3,51,35,1,357,2,34,1,3,5,6];
var highestCount = 0;
for(var i=0; i<=countArray.length; i++){
if(countArray[i]>=highestCount){
highestCount = countArray[i]
}
}
console.log("Highest Count is " + highestCount);
answered Feb 17, 2021 at 17:21
В этом посте мы обсудим, как найти минимальный и максимальный элемент массива в JavaScript.
JavaScript Math
класс предлагает max()
а также min()
функции, которые возвращают наибольшее и наименьшее значение среди заданных чисел соответственно. Вы можете использовать их, чтобы найти максимум и минимум в массиве:
1. Использование Array.prototype.reduce()
функция
Рекомендуемый подход заключается в использовании Array.reduce() найти максимальный и минимальный элемент в массиве. Это работает путем сравнения каждого значения массива:
const min = arr => arr.reduce((x, y) => Math.min(x, y)); const max = arr => arr.reduce((x, y) => Math.max(x, y)); var arr = [ 6, 3, 5, 2, 9 ]; console.log(«Min:», min(arr)); console.log(«Max:», max(arr)); /* результат: Мин: 2 Макс: 9 */ |
Скачать Выполнить код
2. Использование Function.prototype.apply()
функция
Для массивов с меньшим количеством элементов вы можете использовать Function.prototype.apply() метод поиска максимального и минимального значения в числовом массиве. Следующий пример демонстрирует.
var arr = [ 6, 3, 5, 2, 9 ]; console.log(«Min:», Math.min.apply(null, arr)); console.log(«Max:», Math.max.apply(null, arr)); /* результат: Мин: 2 Макс: 9 */ |
Скачать Выполнить код
3. Использование оператора спреда
В качестве альтернативы вы можете использовать оператор Spread (...)
который предлагает более короткий синтаксис записи apply
рассмотренный выше метод:
var arr = [ 6, 3, 5, 2, 9 ]; console.log(«Min:», Math.min(...arr)); console.log(«Max:», Math.max(...arr)); /* результат: Мин: 2 Макс: 9 */ |
Скачать Выполнить код
Как apply()
метод, мы должны использовать его только для массивов с небольшим количеством элементов, так как это может привести к неправильному выводу при использовании с большими массивами. Это связано с тем, что элементы массива передаются как параметры функции.
Это все о поиске минимального и максимального элементов массива в JavaScript.
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования
Для того, чтобы найти максимальный элемент в массиве, можно воспользоваться не только агрегацией. Давайте обратимся к стандартным возможностям языка и рассмотрим метод Math.max.apply():
const numbers = [-94, 87, 12, 0, -67, 32];
const maxValue = Math.max.apply(null, numbers);
//обратите внимание, что в записи данного метода обязателен null.
//Если забыть в записи данного выражения null, то в переменную maxValue вернётся -Infinity.
console.log(maxValue); // => 87
Есть ещё более хитрый способ использовать метод Math.max():
Для этого вспомним про spread оператор.
const numbers = [-94, 87, 12, 0, -67, 32];
const maxValue = Math.max(...numbers);
console.log(maxValue); // => 87
И невозможно не упомянуть про библиотеку Lodash с методом _.max():
const numbers = [-94, 87, 12, 0, -67, 32];
const maxValue = _.max(numbers);
console.log(maxValue); // => 87
Документация:
- Math.max.apply()
- _.max()
In this article, I’m going to explain how to solve Free Code Camp’s “Return Largest Numbers in Arrays” challenge. This involves returning an array with the largest numbers from each of the sub arrays.
There are the three approaches I’ll cover:
- with a FOR loop
- using the reduce() method
- using Math.max()
The Algorithm Challenge Description
Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i].
function largestOfFour(arr) {
return arr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
Provided test cases
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return an array.
largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return [27,5,39,1001].
largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]) should return [9, 35, 97, 1000000].
Approach #1: Return the Largest Numbers in a Array With a For Loop
Here’s my solution, with embedded comments to help you understand it:
function largestOfFour(arr) {
// Step 1. Create an array that will host the result of the 4 sub-arrays
var largestNumber = [0,0,0,0];
// Step 2. Create the first FOR loop that will iterate through the arrays
for(var arrayIndex = 0; arrayIndex < arr.length; arrayIndex++) {
/* The starting point, index 0, corresponds to the first array */
// Step 3. Create the second FOR loop that will iterate through the sub-arrays
for(var subArrayIndex = 0; subArrayIndex < arr[arrayIndex].length; subArrayIndex++) {
/* The starting point, index 0, corresponds to the first sub-array */
if(arr[arrayIndex][subArrayIndex] > largestNumber[arrayIndex]) {
largestNumber[arrayIndex] = arr[arrayIndex][subArrayIndex];
/* FOR loop cycles
arrayIndex => i
subArrayIndex => j
Iteration in the first array
For each iteration: arr[i][j] largestNumber[i] if arr[i][j] > largestNumber[i]? then largestNumber[i] = arr[i][j]
First iteration: arr[0][0] => 4 largestNumber[0] => 0 4 > 0? => TRUE then largestNumber[0] = 4
Second iteration: arr[0][1] => 5 largestNumber[0] => 4 5 > 4? => TRUE then largestNumber[0] = 5
Third iteration: arr[0][2] => 1 largestNumber[0] => 5 1 > 5? => FALSE then largestNumber[0] = 5
Fourth iteration: arr[0][3] => 3 largestNumber[0] => 5 3 > 5? => FALSE then largestNumber[0] = 5
Fifth iteration: arr[0][4] => FALSE largestNumber[0] => 5 largestNumber = [5,0,0,0]
Exit the first array and continue on the second one
Iteration in the second array
For each iteration: arr[i][j] largestNumber[i] if arr[i][j] > largestNumber[i]? then largestNumber[i] = arr[i][j]
First iteration: arr[1][0] => 13 largestNumber[1] => 0 13 > 0? => TRUE then largestNumber[1] = 13
Second iteration: arr[1][1] => 27 largestNumber[1] => 13 27 > 13? => TRUE then largestNumber[1] = 27
Third iteration: arr[1][2] => 18 largestNumber[1] => 27 18 > 27? => FALSE then largestNumber[1] = 27
Fourth iteration: arr[1][3] => 26 largestNumber[1] => 27 26 > 27? => FALSE then largestNumber[1] = 27
Fifth iteration: arr[1][4] => FALSE largestNumber[1] => 27 largestNumber = [5,27,0,0]
Exit the first array and continue on the third one
Iteration in the third array
For each iteration: arr[i][j] largestNumber[i] if arr[i][j] > largestNumber[i]? then largestNumber[i] = arr[i][j]
First iteration: arr[2][0] => 32 largestNumber[2] => 0 32 > 0? => TRUE then largestNumber[2] = 32
Second iteration: arr[2][1] => 35 largestNumber[2] => 32 35 > 32? => TRUE then largestNumber[2] = 35
Third iteration: arr[2][2] => 37 largestNumber[2] => 35 37 > 35? => TRUE then largestNumber[2] = 37
Fourth iteration: arr[2][3] => 39 largestNumber[2] => 37 39 > 37? => TRUE then largestNumber[2] = 39
Fifth iteration: arr[2][4] => FALSE largestNumber[2] => 39 largestNumber = [5,27,39,0]
Exit the first array and continue on the fourth one
Iteration in the fourth array
For each iteration: arr[i][j] largestNumber[i] if arr[i][j] > largestNumber[i]? then largestNumber[i] = arr[i][j]
First iteration: arr[3][0] => 1000 largestNumber[3] => 0 1000 > 0? => TRUE then largestNumber[3] = 1000
Second iteration: arr[3][1] => 1001 largestNumber[3] => 1000 1001 > 1000? => TRUE then largestNumber[3] = 1001
Third iteration: arr[3][2] => 857 largestNumber[3] => 1001 857 > 1001? => FALSE then largestNumber[3] = 1001
Fourth iteration: arr[3][3] => 1 largestNumber[3] => 1001 1 > 1001? => FALSE then largestNumber[3] = 1001
Fifth iteration: arr[3][4] => FALSE largestNumber[3] => 1001 largestNumber = [5,27,39,1001]
Exit the FOR loop */
}
}
}
// Step 4. Return the largest numbers of each sub-arrays
return largestNumber; // largestNumber = [5,27,39,1001];
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
And here it is without my comments:
function largestOfFour(arr) {
var largestNumber = [0,0,0,0];
for(var arrayIndex = 0; arrayIndex < arr.length; arrayIndex++) {
for(var subArrayIndex = 0; subArrayIndex < arr[arrayIndex].length; subArrayIndex++) {
if(arr[arrayIndex][subArrayIndex] > largestNumber[arrayIndex]) {
largestNumber[arrayIndex] = arr[arrayIndex][subArrayIndex];
}
}
}
return largestNumber;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
Approach #2: Return the Largest Numbers in a Array With Built-In Functions — with map() and reduce()
For this solution, you’ll use two methods: the Array.prototype.map() method and the Array.prototype.reduce() method.
- The map() method creates a new array with the results of calling a provided function on every element in this array. Using map will call a provided callback function once for each element in an array, in order, and constructs a new array from the results.
- The reduce() method applies a function against an accumulator and each value of the array to reduce it to a single value.
The ternary operator is the only JavaScript operator that takes three operands. This operator is used as a shortcut for the if statement.
(currentLargestNumber > previousLargestNumber) ? currentLargestNumber : previousLargestNumber;
This can also be read as:
if (currentLargestNumber > previousLargestNumber == true) {
return currentLargestNumber;
} else {
return previousLargestNumber;
}
Here’s my solution, with embedded comments:
function largestOfFour(mainArray) {
// Step 1. Map over the main arrays
return mainArray.map(function (subArray){ // Step 3. Return the largest numbers of each sub-arrays => returns [5,27,39,1001]
// Step 2. Grab the largest numbers for each sub-arrays with reduce() method
return subArray.reduce(function (previousLargestNumber, currentLargestNumber) {
return (currentLargestNumber > previousLargestNumber) ? currentLargestNumber : previousLargestNumber;
/* Map process and Reduce method cycles
currentLargestNumber => cLN
previousLargestNumber => pLN
Iteration in the first array
For each iteration: cLN pLN if (cLN > pLN) ? then cLN else pLN
First iteration: 4 0 4 > 0? => TRUE 4 /
Second iteration: 5 4 5 > 4? => TRUE 5 /
Third iteration: 1 5 1 > 5? => FALSE / 5
Fourth iteration: 3 5 3 > 5? => FALSE / 5
Fifth iteration: / 5 returns 5
Exit the first array and continue on the second one
Iteration in the second array
For each iteration: cLN pLN if (cLN > pLN) ? then cLN else pLN
First iteration: 13 0 13 > 0? => TRUE 13 /
Second iteration: 27 13 27 > 13? => TRUE 27 /
Third iteration: 18 27 18 > 27? => FALSE / 27
Fourth iteration: 26 27 26 > 27? => FALSE / 27
Fifth iteration: / 27 returns 27
Exit the first array and continue on the third one
Iteration in the third array
For each iteration: cLN pLN if (cLN > pLN) ? then cLN else pLN
First iteration: 32 0 32 > 0? => TRUE 32 /
Second iteration: 35 32 35 > 32? => TRUE 35 /
Third iteration: 37 35 37 > 35? => TRUE 37 /
Fourth iteration: 39 37 39 > 37? => TRUE 39 /
Fifth iteration: / 39 returns 39
Exit the first array and continue on the fourth one
Iteration in the fourth array
For each iteration: cLN pLN if (cLN > pLN) ? then cLN else pLN
First iteration: 1000 0 1000 > 0? => TRUE 1000 /
Second iteration: 1001 1000 1001 > 1000? => TRUE 1001 /
Third iteration: 857 1001 857 > 1001 => FALSE / 1001
Fourth iteration: 1 1001 1 > 1001? => FALSE / 1001
Fifth iteration: / 1001 returns 1001
Exit the first array and continue on the fourth one */
}, 0); // 0 serves as the context for the first pLN in each sub array
});
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
And here it is without comments:
function largestOfFour(mainArray) {
return mainArray.map(function (subArray){
return subArray.reduce(function (previousLargestNumber, currentLargestNumber) {
return (currentLargestNumber > previousLargestNumber) ? currentLargestNumber : previousLargestNumber;
}, 0);
});
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
Approach #3: Return the Largest Numbers in a Array With Built-In Functions — with map() and apply()
For this solution, you’ll use two methods: the Array.prototype.map() method and the Function.prototype.apply() method.
- The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).
You can pass an array of arguments to a function by using the apply() method and the function will execute the items in the array.
Such functions are known as variadic functions, and they can accept any number of arguments instead of a fixed one.
The Math.max() function returns the largest of zero or more numbers, and we can pass any number of arguments.
console.log(Math.max(4,5,1,3)); // logs 5
But you can’t pass an array of numbers to the method like this:
var num = [4,5,1,3];
console.log(Math.max(num)); // logs NaN
This is where the apply() method turns out to be useful:
var num = [4,5,1,3];
console.log(Math.max.apply(null, num)); // logs 5
Note that the first argument to apply() sets the value of ‘this’, not used in this method, so you pass null.
Now that you have a method to return the largest number in a array, you can loop through each sub-arrays with the map() method and return all largest numbers.
Here’s my solution, with embedded comments:
function largestOfFour(mainArray) {
// Step 1. Map over the main arrays
return mainArray.map(function(subArray) { // Step 3. Return the largest numbers of each sub-arrays => returns [5,27,39,1001]
// Step 2. Return the largest numbers for each sub-arrays with Math.max() method
return Math.max.apply(null, subArray);
});
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
And without comments:
function largestOfFour(mainArray) {
return mainArray.map(function(subArray) {
return Math.max.apply(null, subArray);
});
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
I hope you found this helpful. This is part of my “How to Solve FCC Algorithms” series of articles on the Free Code Camp Algorithm Challenges, where I propose several solutions and explain step-by-step what happens under the hood.
Three ways to repeat a string in JavaScript
In this article, I’ll explain how to solve freeCodeCamp’s “Repeat a string repeat a string” challenge. This involves…
Two ways to confirm the ending of a String in JavaScript
In this article, I’ll explain how to solve freeCodeCamp’s “Confirm the Ending” challenge.
Three Ways to Reverse a String in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Reverse a String”
Three Ways to Factorialize a Number in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Factorialize a Number”
Two Ways to Check for Palindromes in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Check for Palindromes”.
Three Ways to Find the Longest Word in a String in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Find the Longest Word in a String”.
Three Ways to Title Case a Sentence in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Title Case a Sentence”.
If you have your own solution or any suggestions, share them below in the comments.
Or you can follow me on Medium, Twitter, Github and LinkedIn, right after you click the green heart below
#StayCurious, #KeepOnHacking & #MakeItHappen!
Additional Resources
- for — MDN
- array.length — MDN
- map() method — MDN
- reduce() method — MDN
- Ternary Operator — MDN
- apply() method — MDN
- Math.max() — MDN
- this — MDN
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started