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

社会主义新天地 提交于 2020-01-03 14:24:20

问题


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.


回答1:


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);



回答2:


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);



回答3:


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);



回答4:


You can simply merged all the nested array into a single array and then find minimum and maximum value by using Math.min.apply(null, array) and Math.max.apply(null, array)

var arr = [[12,45,75], [54,45,2],[23,54,75,2]];
var merged = [].concat.apply([], arr);
var max = Math.max.apply(null, merged);
var min = Math.min.apply(null, merged);
console.log(max,min)



回答5:


Solution without concatenation, which works for any level of nesting

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

function findMaxFromNestedArray(arr) {
  let max = Number.MIN_SAFE_INTEGER;
  
  for (let item of arr) {
    if(Array.isArray(item)) {
      let maxInChildArray = findMaxFromNestedArray(item);
      if (maxInChildArray > max) {
        max = maxInChildArray;
      }
    } else {
      if (item > max) {
        max = item;
      }
    }
  }
  
  return max;
}

console.log(findMaxFromNestedArray(arr))



回答6:


Solution with only one reduce:

const getMaxMin = (flattened) => {
return flattened.reduce(
        (a, b) => {            
            return {
                maxVal: Math.max(b, a.maxVal),
                minVal: Math.min(b, a.minVal),                
            };
        },
        {
            maxVal: -Infinity,
            minVal: Infinity,            
        }
    );
}
const flatSingle = arr => [].concat(...arr)
const maxMin = getMaxMin(flatSingle(arr))
console.log(maxMin);


来源:https://stackoverflow.com/questions/47691738/find-the-max-and-min-element-out-of-all-the-nested-arrays-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!