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 3 years have passed since last update.

javascriptを使用して配列の中から最も近い値を取得する方法

Last updated at Posted at 2021-04-24

qiita初投稿です。備忘録として投稿させていただきます。

const val = 8 // 対象値
const closest = [1, 10, 7, 2, 4].reduce((a, b) => {
    return Math.abs(b - val) < Math.abs(a - val) ? b : a;
});
console.log(closest); // Output: 7

こちらの記事を参考にしました。
https://www.gavsblog.com/blog/find-closest-number-in-array-javascript

0
0
0

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?