最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

min max values 2D array javascript - Stack Overflow

programmeradmin3浏览0评论

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!

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!

Share Improve this question edited May 23, 2017 at 12:13 CommunityBot 11 silver badge asked Mar 8, 2016 at 6:24 BudBud 1,5015 gold badges23 silver badges42 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 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

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

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

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

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

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)

发布评论

评论列表(0)

  1. 暂无评论