Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an array is descending, ascending or not sorted?

Tags:

javascript

I'm just beginning with programming using javascript and I need to practice some questions to get EXP with the logic of code build. I got this question for homework but I can't make it work for some reason, even though it seems "logic" to me. Check if an array is descending, ascending or not sorted using loops.

I'm just a noob so please try and help me figure this out as I only got to loops in my studies (: this is the code I wrote:

        var array = [1, 2, 3, 7 ];
        var d = 0;
        var c =0 ;
        var b = 1;
        var a = 0;
        for (var i = 1; i <= array.length; i++)
            {
                if (array[c]<array[b] && a!== -1  ){
                   d = -1;
                   c =c+1;
                   b = b+1;
                   if(c==array.length){
                    console.log("asc");
                     break;
                   }else{
                     continue;
                }

                } else if (array[c]>array[b] && d!==-1 ){
                           a = -1;
                           d= d+1;
                           b = b+1;
                    if(i=array.length){
                    console.log("dsc");
                    break;
               }else{continue;}

               } else{

                    console.log("unsorted array");
                    break;
                }

            }
like image 540
Maikel Bazov Avatar asked Jul 08 '17 20:07

Maikel Bazov


1 Answers

Array.prototype.every passes its predicate an index, which you can use to get an element’s predecessor:

function isAscending(arr) {
    return arr.every(function (x, i) {
        return i === 0 || x >= arr[i - 1];
    });
}

Here, we’re checking that every item (x) is greater than or equal to the item before it (arr[i - 1]) or has no item before it (i === 0).

Flip >= to <= for isDescending.

like image 113
Ry- Avatar answered Sep 27 '22 18:09

Ry-