获取数组中最接近的数字 [英] Get the closest number out of an array

查看:97
本文介绍了获取数组中最接近的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从负1000到正1000的数字,并且我有一个带有数字的数组。像这样:

I have a number from minus 1000 to plus 1000 and I have an array with numbers in it. Like this:

[2, 42, 82, 122, 162, 202, 242, 282, 322, 362]

我希望将得到的数字更改为最接近数组的数字。

I want that the number I've got changes to the nearest number of the array.

例如,我得到 80 作为数字,我希望它得到 82

For example I get 80 as number I want it to get 82.

推荐答案

ES5版本:

var counts = [4, 9, 15, 6, 2],
  goal = 5;

var closest = counts.reduce(function(prev, curr) {
  return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
});

console.log(closest);

这篇关于获取数组中最接近的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆