Is there a simple way to find a max number in a array given below in JavaScript?
[3,4,[22,21],5,9,5]
Math.max.apply(null,numbers)
gives NaN
.
Is there a simple way to find a max number in a array given below in JavaScript?
[3,4,[22,21],5,9,5]
Math.max.apply(null,numbers)
gives NaN
.
Your example is an array with another array nested one level deep. Assuming only one level of nesting, first you flatten the array, then you apply the Math.max
trick to it:
var a = [3,4,[22,21],5,9,5];
var max = Math.max.apply(Math, [].concat.apply([], a));
console.log(max);
Here's a solution using a version of reduce
which handles nested arrays.
function nestedReduce(array, fn, initial) {
return array.reduce(function(result, elt) {
return fn(result, Array.isArray(elt) ? nestedReduce(elt, fn, initial) : elt);
}, initial);
}
console.log(nestedReduce([3,4,[22,21],5,9,5], Math.max, -Infinity));
This will handle any level of nesting.
You could use a recursion with Array#reduce
.
This works for multiple nested arrays.
var array = [3, 4, [22, 21], 5, 9, 5, [[[42]]]],
maxValue = array.reduce(function max(r, a, i) {
var v = Array.isArray(a) ? a.reduce(max, undefined) : a;
return !i || r < v ? v : r;
}, undefined);
console.log(maxValue);
Edit suggested by torazaburo with -Infinity
and Math.max
.
var array = [3, 4, [22, 21], 5, 9, 5, [[[42]]]],
maxValue = array.reduce(function max(r, a, i) {
return Math.max(r, Array.isArray(a) ? a.reduce(max, -Infinity) : a);
}, -Infinity);
console.log(maxValue);
I would do as follows;
function getMax(a){
return Math.max(...a.map(e => Array.isArray(e) ? getMax(e) : e));
}
var arr = [3, 4, [22, 21], 5, 9, 5, [[[42]]], 41];
console.log(getMax(arr));