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;
}
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With