0
0

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-23

##お題
配列(第一引数)を小さい数字から並べ替えて、目的の数字(第二引数)が入る添字を返す。

script.js
function getIndexToIns(arr, num) {
//write your code.
}
getIndexToIns([5,1,2,3,4], 1.5);

##出力結果 例

script.js
([40, 60], 50) // 1
([3, 10, 5], 3) // 0
([2, 5, 10], 15) // 3
([2, 20, 10], 19) // 2
([5, 3, 20, 3], 5) // 2
([10, 20, 30, 40, 50], 30) // 2

##使った関数
sort()

##コード

script.js
function getIndexToIns(arr, num) {
   arr.sort(function(a, b) {
    return a - b;
  });  
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] >= num)
      return i;
  }
  return arr.length;
}

getIndexToIns([1,2,3], 1.5);//1

##考え方
・sort()で配列をならべかえる。
a - b だと小さい数字から、 b - a だと大きい数字から並ぶ。

・for文でarr[i]と目的の数字(num)を比較する。
同じ以上の値が返るとき、iが目的の数字が入る場所になる。

###他にもコードが浮かんだ方、コメントお待ちしてます。

0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?