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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With