是否可以从javascript中的数组中过滤出连续的数字?

Is it possible to filter consecutive numbers from an array in javascript?

我有下面这样的数组。

[1,2,3, 10, 15, 24,25,26,27]

我想要的是过滤掉不连续的数字,不包括系列中的第一个数字,但保留系列中的最后一个数字,如下所示。

[2,3, 25,26,27]

我是编码新手,我还不确定如何编写这段代码,但我模拟了伪代码,你能检查一下我的逻辑是否正常吗?

Var startArray = [1,2,3,10,15,24,25,26,27];

Var endArray = [ ];

Loop: while the numbers left in the start array
GET:startArray的第一个数

IF:第一个数字是1
移动:到数组中的下一个数字

IF:数组中的当前数+1减去数组中的当前数-1===2
PUSH:当前数到endArray

ELSE IF:当前数-1 ===1
PUSH:当前数到endArray

如果

结束

循环结束

感谢您的帮助。

这是我的想法。

const start = [1, 2, 3, 10, 15, 24, 25, 26, 27];
let end = new Array(), i = 0;
while (i < start.length) {
  let j = 2;
  if (start[i+j-2] + 1 == start[i+j-1])
    end.push(start[i+j-2], start[i+j-1]);
  else { i++; continue; }
  while (i+j < start.length && start[i+j-1] + 1 == start[i+j])
    end.push(start[i+j++]);
  i += j;
}

解释:第一个 while 循环遍历每个连续数字序列。变量j首先用于检查期望序列的第一个和第二个元素,如果它们不连续,则将i递增1,改变下一个期望序列的起点连续的数字。如果它们是连续的数字,它会将它们都压入 end 数组,并继续嵌套循环,检查 j-1 元素(当前序列的第一个元素是否总是 i ) 和 j 元素是连续的,如果它们是连续的,它将序列的 j 元素添加到 end 数组中。最后,当嵌套循环完成执行时,它将 j 添加到 i,以更改下一个序列的起点。


我知道解释的很乱,但希望它能帮助你理解。

我们可以使用数组内置方法filter。在评论中解释。

const start = [1, 2, 3, 10, 15, 24, 25, 26, 27]

const result = start.filter((el, i) => {
  // if `el` is the any element in consecutive sequence except the first
  if (el - 1 === start[i - 1]) return true

  // else it is consecutive sequence of size 1 (10, 15) in the example,
  // or it is first element in consecutive sequence of size greater than 1
  return false
})

console.log(result)

您只需遍历所有内容并简单地检查当前数字是否比前一个数字大一个。如果是这样,将其推送到结果数组:

var startArray = [1, 2, 3, 10, 15, 24, 25, 26, 27];
var endArray = [];

for(var i = 0; i < startArray.length; i++) {
  if(startArray[i] - 1 === startArray[i - 1]) {
    endArray.push(startArray[i]);
  }
}

$.writeln(endArray); // => 2, 3, 25, 26, 27