Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a array like so:

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

I want to find out the largest element and the smallest element out of all the elements in the nested array:

The min should be: 2

and

Max should be 75

I tried the functions below but they do not work:

    function Max(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let max = Math.max.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.max.apply(window, arrs[i].filter(f)))>max) max=m;
        }
        return max;
    }
    function Min(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let min = Math.min.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.min.apply(window, arrs[i].filter(f)))>min) min=m;
        }
        return min;
    }

It gives out Max as 75 and min as 12.

Any guidance will be appreciated.

Also tried other answers in SO but none help.

The answer at Merge/flatten an array of arrays in JavaScript? resolves the problem of merging arrays.

Whereas my problem is to keep the array as is and perform operations.

like image 941
Shakti Phartiyal Avatar asked Dec 07 '17 09:12

Shakti Phartiyal


2 Answers

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);
like image 167
klugjo Avatar answered Nov 15 '22 21:11

klugjo


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);
like image 34
gurvinder372 Avatar answered Nov 15 '22 22:11

gurvinder372