javascript 如何确定数组中的数字是否为连续顺序,数字必须为3个或更多数字

elcex8rz  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(126)

我有一个数组和,我想知道值是否是连续的。我希望是连续的3个数字或更多。如果数字是连续的3个或更多数字,那么折扣将被应用。我提供了一些例子,它使我想实现的清晰。

["1", "2", "3"] -> OK
["5", "6", "7"] -> OK
["1", "2", "3", "4", "5", "6", "7"] -> OK
["1", "2", "3", "4", "5"] -> OK
["1", "2", "3","4","5"] - > OK
["1", "2"] -> NOT OK
["4", "7"] -> NOT OK
["1", "2", "4"] -> NOT OK
["1", "2", "7"] -> NOT OK

let customNumbersArray = ["1", "2", "3", "4", "5", "6", "7",];

customNumbersArray.forEach(num => {
if(num == consecutive) {
// ???
} else {
// ???
}
})
qxgroojn

qxgroojn1#

只需遍历数组并将每个元素与其前一个元素进行比较:

const data = [
    ["1", "2", "3"],
    ["5", "6", "7"],
    ["1", "2", "3", "4", "5", "6", "7"],
    ["1", "2", "3", "4", "5"],
    ["1", "2", "3","4","5"],
    ["1", "2"],
    ["4", "7"],
    ["1", "2", "4"],
    ["1", "2", "7"],
  ]
  const isConsecutive = (nums) => nums.length >= 3 && nums.every((n,i) => i === 0 || n - nums[i-1] === 1)
  data.forEach(d => console.log(JSON.stringify(d), isConsecutive(d)))

相关问题