4

I've found lots of similar posts, but none yet that fully satisfy the question: How can I get the min & max values from the following 2D array in javascript?

[[1,2,3],[4,5,6],[7,8,9]]

i.e., return 1 and 9.

this question isn't quite what I'm after (as the user wants to ignore col 0), and here asks only for a 1D array.

The accepted answer here asks only for the first value of each set.

Can anyone point me to the correct (accepted) method? Many thanks!

Community
  • 1
  • 1
Liz
  • 1,151
  • 2
  • 17
  • 34

5 Answers5

3

How about flattening the array, then using Math.max.apply and Math.min.apply:

var arr = [[1,2,3],[4,5,6],[7,8,9]].reduce(function (p, c) {
  return p.concat(c);
});

var max = Math.max.apply(null, arr); // 9
var min = Math.min.apply(null, arr); // 1
Andy
  • 39,764
  • 8
  • 53
  • 80
0

Try to use traditional way of finding min and max from an array,

var x = [[1, 2, 3],[4, 5, 6],[7, 8, 9]];
var min,max;
x.forEach(function(itm) {
  itm.forEach(function(itmInner) {
    min = (min == undefined || itmInner<min) ? itmInner : min;
    max = (max == undefined || itmInner>max) ? itmInner : max;
  });
});
console.log(max,min); // 9, 1

DEMO


And you can see a performance test below,

Performance Test

Rajaprabhu Aravindasamy
  • 63,064
  • 13
  • 90
  • 119
0

Use Array.prototype.reduce in order to flatten the array and Array.prototype.sort or Math.Min\Math.Max in order to find the max\min values.

var arr = [[9,2,3],[4,5,6],[7,8,1]];
var flattenedArr = arr.reduce(function(arr1, arr2) {  return arr1.concat(arr2)});

var sorted = flattenedArr.sort();
var min = sorted[0];
var max = sorted[sorted.length - 1];
Amir Popovich
  • 26,624
  • 8
  • 44
  • 88
0

try this

var array = String([[1,2,3],[4,5,6],[7,8,9]]).split(",").map( function(value){ return parseInt(value); } );

var max_of_array = Math.max.apply(Math, array);
var min_of_array = Math.min.apply(Math, array);
gurvinder372
  • 61,170
  • 7
  • 61
  • 75
0

function minMaxIn2D(arr) {
  var min,max;
  for(var i in arr) {
    for(var j in arr[i]){
      min = min - arr[i][j] <= 0 ? min : arr[i][j] ;
      max = max - arr[i][j] >= 0 ?  max: arr[i][j]; 
    }

  }
  console.log(min, max)
}
saikumar
  • 973
  • 5
  • 8