5

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,421
  • 5
  • 21
  • 39

6 Answers6

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
  • 61,948
  • 13
  • 68
  • 95
1

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
  • 66,513
  • 17
  • 101
  • 130
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
  • 29,350
  • 9
  • 53
  • 99
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
  • 66,980
  • 10
  • 72
  • 94
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
  • 1,041
  • 6
  • 10
0

using flat

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

const max = Math.max(...arr.flat())
const min = Math.min(...arr.flat())

console.log(min, max)
binga58
  • 153
  • 7