Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

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

I have arrays like this one below.

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

What I want is to filter out the non consecutive numbers excluding the first number in a series but keeping the last in a series like this below.

[2,3, 25,26,27]

I am new to coding and I'm not sure how to write this code yet but I have mocked up pseudocode, would you check this and see if my logic is on track?

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

Var endArray = [ ];

Loop: while there are numbers left in the start array ?
?GET: The first number of the startArray

IF: the first number is 1
?MOVE: to next number in the array

IF: the current number + 1 in the array subtracted by the current number -1 in the array === 2
?PUSH: current number into endArray

ELSE IF: the current number -1 ===1
?PUSH: current number into endArray

END IF

END LOOP

Thank you for your help.

question from:https://stackoverflow.com/questions/66067826/is-it-possible-to-filter-consecutive-numbers-from-an-array-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will just have to loop over everything and simply check, if the current number is one higher than the previous number. If so, push it to your resulting array:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...