Kaan Karaca
Kaan Karaca

Reputation: 190

How to get largest value in multi-dimensional array

function largestOfFour(arr) {
var max = 0;
var newArr = [];

for (var i = 0; i < arr.length; i++) {
    for (var j = i; j < arr.length; j++) {
        max = Math.max(max, arr[i][j]);
    }
    newArr.push(max);
 }
 return newArr;
}

Here is my code. It works for me but I want to know is there any other sort way to do this?

Upvotes: 0

Views: 184

Answers (3)

Rajesh
Rajesh

Reputation: 24955

You can try something like this:

Idea, Math.max takes n arguments and gives you the max value. Using .apply you can pass parameters as array. Combining both will give you max value in an array.

Apply

var data = [
  [1, 2, 3, 4],
  [10, 20, 200, 31],
  [21, 3, 444, 133],
  [0, 0, 90, 1]
];
var max_arr = data.map(function(a) {
  return Math.max.apply(this, a);
});
console.log(max_arr)

Sort + slice + pop

var data = [
  [1, 2, 3, 4],
  [10, 20, 200, 31],
  [21, 3, 444, 133],
  [0, 0, 90, 1]
];

var max_arr = data.map(function(a) {
  return a.sort().slice(-1).pop()
});

console.log(max_arr)

Upvotes: 0

vorillaz
vorillaz

Reputation: 6296

You may use the spread operator as:

var data = [
  [1, 2, 3, 4],
  [10, 20, 200, 31],
  [21, 3, 444, 133],
  [0, 0, 90, 1]
];
const max = Math.max(...data.map(inner => Math.max(...inner)));
console.log(max);

Upvotes: 0

CD..
CD..

Reputation: 74166

Try this:

function largestOfFour(arr) {
  return arr.map(function(item){
    return Math.max.apply(null, item);
  });
}

Upvotes: 3

Related Questions