24
25

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.

[javascript]配列から最も近い値を探す

Posted at

jsで配列から最も近い値を探すやり方を調べたけどあんまり出てこなかったのでメモ。

数値配列から、指定の値に最も近い値のindexを取り出す。

var value = 100; // 調べたい値
var array = [1,123,13,84,255,3,136,96,117,62]; // 調べたい配列
var diff = [];
var index = 0;

$(array).each(function(i,val){
  diff[i] = Math.abs(value - val);
  index = (diff[index] < diff[i]) ? index : i;
});

indexじゃなくて値がほしいときは、array[index]を見れば良い。

まあ特に難しいことはなかった。

関数やクラスにして使いまわすというよりは、状況に応じて使いやすいように変えればいいと思います。

###参考
http://qiita.com/PianoScoreJP/items/755e7d638e4381b5de24

24
25
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
24
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?