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

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

问题描述

我有一个从负 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天全站免登陆