javascript – Counting Valleys – HackerRank Challenge – Filter the elements of the matrix that are equal to the previous element

For this challenge in HackerRank:

A valley is a sequence of consecutive steps below sea level, which begins with a step down from sea level and ends with a step towards sea level.

Given the sequence of steps up and down Gary during his last walk, find and print the amount of valleys he walked through.

For example, if Gary's route is s =[DDUUUUDD], first enter a valley of 2 units deep. Then climb and climb a mountain of 2 units in height. Finally, return to sea level and finish the trek.

I came up with a solution, but I'm sure it can be optimized:

function countingValleys (n, s) {
leave heighttracker = [];
leave height = 0;
for (be i = 0; i <s.length; i ++) {
yes[i] === "D") {
height--;
heightTracker.push (height);
}
yes[i] === "U") {
height ++;
heightTracker.push (height);
}
}
leave planeTracker = [];
for (be j = 0; j <heightTracker.length; j ++) {
yes (heighttracker)[j] < 0) {
            planeTracker.push("valley");
        }
        if (heightTracker[j] >    0) {
planeTracker.push ("mountain");
}
yes (heighttracker)[j] === 0) {
planeTracker.push ("plane");
}
}
leave newArray = [];
for (be k = 0; k <planeTracker.length; k ++) {
yes[k] === planeTracker[k - 1]) {
continue;
}
yes[k] ! == planeTracker[k - 1]) {
newArray.push (planeTracker[k]);
}
}
let's say valleyCount = 0;
for (be l = 0; l <newArray.length; l ++) {
if (newArray[l] === "valley") {
valleyCount ++;
}
}
return valleyCount;
}

My logic was to keep track of all negative and positive values ​​in s.

  • Yes height tracker[j] is negative, push "valley" in avionist
  • Yes height tracker[j] it's positive, push "mountain" in avionist
  • Otherwise, push "flat" on avionist

So at that point, I'm left with:

[ 'valley', 'valley', 'valley', 'flat', 'valley', 'valley', 'valley', 'valley', 'valley', 'flat', 'mountain', 'flat' ]

And I wonder, is there any way to filter elements that are the same as the previous elements? The objective was to generate the matrix:

[ 'valley', 'flat', 'valley', 'flat', 'mountain', 'flat'] and then count the number of times the word "valley" appears in that matrix. As you can see, I did this with a for loop. But I wonder what other suggestions you would have, maybe the .filter() method?