首页 > 解决方案 > 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?

标签: javascript

解决方案


通过排序数组,您可以获得实际元素之前的第四个元素并检查增量。

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]));


推荐阅读