K
K
kuzubina2020-03-02 11:30:04
JavaScript
kuzubina, 2020-03-02 11:30:04

How to find consecutive elements in an array?

There is an array of this kind [0,1,3,99,4,7,8,9,11,12,15,8,9]
For example, I need to find out how many times the sequence of numbers 8.9 comes across (in this example, 2 times)
How to calculate it, tell me pliz

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Valentin Mikhailov, 2020-03-02
@kuzubina

const array = [0,1,3,99,4,7,8,9,11,12,15,8,9];
let count = 0;
for (let i = 0; i < array.length; i++) {
    if ( array[i] === 8 && array[i+1] === 9 ) {
        count++;
    }
}

X
xmoonlight, 2020-03-02
@xmoonlight

Cycle through the positions of the array elements with a decreasing "window" of elements to look at: from the longest N-1 to 1.
The "window" matched the available pattern for the given window size -> increment the number of the given sequence.
Did not match -> new sequence element for given "window" size.
Result: an array of all consecutive unique combinations with an indication of the number of their repetitions in the original array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question