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!

6 Answers 6

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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

Comments

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

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.