5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

js 多次元配列 一番大きい数を取り出す

Last updated at Posted at 2016-12-10

#JavaScript 多次元配列の各配列の一番大きい数字の取り出し方

script.js

function largestOfFour(arr) {
//write your code.
  return newArray;
}

largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]); //欲しい答え [27,5,39,1001] 

script.js
([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])  //欲しい答え [27,5,39,1001] 

([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]) //欲しい答え [9, 35, 97, 1000000]

##一番最初に試したコード

script.js

function largestOfFour(arr) {
  var newArray = [];
  var max = 0;
  for(var i = 0; i < arr.length; i++){
      for(var j = 0 ; j < arr.length; j++){
        if(max < arr[i][j]){
          max = arr[i][j];
        }
        if( j === arr.length-1){
        newArray.push(max);
          max = 0;
        }
      }
  }
  return newArray;
}

largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

##考え方
多次元配列の要素の配列をarr[i],その数字をarr[i][j]で表す。
arr[i][j]をfor文で比較して一番大きいものをmaxに入れる。
要素の配列で比較が終わったら、newArrayにmaxを格納、maxを初期化して次の要素の配列の比較へ。
すべての処理が終わったら newArrayを返す。

##教えていただいたコード

script.js
function largestOfFour(arr) {
  return arr.map(function(subArr){
    return subArr.reduce(function(x,y){
      return Math.max(x,y);
    })
  }).join(',');
}
largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
function largestOfFour(arr) {
  return arr.map(Function.apply.bind(Math.max, null));
}
largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

他にも良い方法がございましたら教えていただけると幸いです。

5
2
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?