Find the Max and Min element out of all the nested arrays in javascript

Assuming ES6

const arr = [[12,45,75], [54,45,2],[23,54,75,2]];

const max = Math.max(...[].concat(...arr));

const min = Math.min(...[].concat(...arr));

console.log(max);

console.log(min);


You can flatten the array first (advantage - will work for nested arrays at multiple levels)

var flattenedArr = [[12,45,75], [54,45,2],[23,54,75,2] ].toString().split(",").map(Number);

Then get the min and max from the flattened array

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

Demo

var flattenedArr = [
  [12, 45, 75],
  [54, 45, 2],
  [23, 54, 75, 2]
].toString().split(",").map(Number);

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

console.log(max, min);


A ES5 recursive approach by checking the type. It works for deep nested arrays.

var array = [[12, 45, 75], [54, 45, 2], [23, 54, 75, 2]],
    min = array.reduce(function min(a, b) {
        return Math.min(Array.isArray(a) ? a.reduce(min) : a, Array.isArray(b) ? b.reduce(min) : b);
    }),
    max = array.reduce(function max(a, b) {
        return Math.max(Array.isArray(a) ? a.reduce(max) : a, Array.isArray(b) ? b.reduce(max) : b);
    });
    
console.log(min, max);

With functions for using as callback.

function flat(f, v) { return Array.isArray(v) ? v.reduce(f) : v; }
function getMin(a, b) { return Math.min(flat(getMin, a), flat(getMin, b)); }
function getMax(a, b) { return Math.max(flat(getMax, a), flat(getMax, b)); }

var array = [[12, 45, 75], [54, 45, 2], [23, 54, 75, 2]],
    min = array.reduce(getMin),
    max = array.reduce(getMax);
    
console.log(min, max);