javascript - JavaScript check if several numbers within a set are within a certain range
问题描述
Basically, I have a list like this in JavaScript.
var times1=[0,100,500,501,502,503,504]
var times2=[0,50,100,150,200,250,300]
And I need to check if any 5 numbers have a range of 10. For example, times1
would be detected as true
or positive as 500,501,502,503,504
are 5 numbers that are within a range of 10. times2
however would be considered false
or negative as all of its numbers are 50 apart.
For this could use a loop that goes through every number to see if it passes the condition, but is there any faster/better way to do this?
解决方案
通过排序数组,您可以获得实际元素之前的第四个元素并检查增量。
Array#some
如果回调返回,则结束迭代true
。
const check = array => array.some((a, i, { [i + 4]: b }) => b - a <= 10);
console.log(check([0, 100, 500, 501, 502, 503, 504]));
console.log(check([0, 50, 100, 150, 200, 250, 300]));
推荐阅读
- javascript - 如何在 Cognos 的日期提示中将月份的第一天设置为默认值
- android-studio - Facebook 个人资料图片未在 android studio 中显示,我同时使用了 glide 和 Picasso
- html - 关注复选框与复选框边框和轮廓不一致
- python - 枕头包是必需的,但我已经有最新版本
- google-cloud-platform - GCP 中是否有中央 API 或语言库来标记所有资源?
- javascript - 我在 Javascript 上的突破克隆的暂停/播放按钮
- javascript - Angular js控制器不向mvc控制器发送数据
- c++ - 从标记为 extern C 的函数调用损坏的类实例方法
- keras - Understanding Keras batch_size vs. batch dimension for LSTM
- spring - Spring Boot 微服务丢弃标头