-1

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
KT B
  • 115
  • 2
  • 9

4 Answers4

4

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);
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

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.

2

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);
Community
  • 1
  • 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 2
    To maintain the semantics of `Math.max`, the maximum of an empty array should be `-Infinity`, not `undefined`. That would also allow you to skip the `!i` check. –  Aug 27 '16 at 08:24
  • Even i haven't used reduce -:) – Redu Aug 27 '16 at 17:14
1

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));
Redu
  • 25,060
  • 6
  • 56
  • 76