Skip to content
Advertisement

How to check if an array is increasing in javascript?

I follow a javascript course and I am stuck with something. We get a website full of excercises and have to make all the test cases turn green.

We have to check if an array is increasing and return true if that is the case.If the next value is the same as the previous the function must also return true. All my test cases return false for some reason? And if I remove the else only one of the test cases is wrong (this one: [0,1,2,3,4,5,0]). Here are the test cases.

JavaScript

Advertisement

Answer

Walk through your code with the debugger, stopping at interesting lines and examining the values. You should be able to find the problem soon enough.

If you want to use a for loop, you can simplify your code, and omit the special casing for 0 and 1, while fixing the top of the loop condition:

JavaScript

If you’re allowed to use ES5 array methods, this can use every:

JavaScript

If you want to make your code more semantic and readable, define a well-named function:

JavaScript

To continue with this factoring, we can separate out two aspects of the solution. The first is to see if one value is the same as or one greater than another. The second is to take pairs of adjacent elements in an array. In other words, we would like to be able to write the solution as

JavaScript

sameOrGreater is easy:

JavaScript

pairs can be written as follows:

JavaScript

You might prefer to write pairs using a generator:

JavaScript

Alternatively we could write a version of map which takes a function to which are fed pairs, as follows:

JavaScript

Now we can write the entire problem as

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement