0

I have an array like below

var nums = ["1", "2", "2", "3", "4", "4", "5"];

Here I am trying to compare the values in array and test whether the values are in ascending order or not.

If two array values are same, I need to skip that. If order is like 1,3,2.. then I will throw an error that they are in wrong order. I want to use pure javascript here.

halex
  • 16,253
  • 5
  • 58
  • 67
Vamshi
  • 186
  • 4
  • 16

3 Answers3

1

Seems easy:

function isAscending(arr){
    asc = true;
    for(var i=1;i<arr.length;i++){
        if(Number(arr[i]) < Number(arr[i-1])){
            asc = false;
            break;
        }
    }
    return asc
}
juvian
  • 15,875
  • 2
  • 37
  • 38
1

I would loop through each pair of items using parseInt() to get the numeric value out of the strings and after the loop, compare the value of the incremented index to the number of pairs.

EDIT: As suggested by Rick Hitchcock, instead of breaking from the loop, we can just return false if any pair is not ascending or equal and true if the whole loop went through.

function isAscending(array) {
    for (var i = 0; i < (array.length - 1); i++) {
        if (parseInt(array[i]) > parseInt(array[i+1])) {
            return false;
        }
    }
    return true;
}
Yaar Hever
  • 81
  • 1
  • 6
1

Using jquery

var num = [1,5,3,3,4,4];
var sortedNum = num.slice(0).sort(function(a,b) {
    return a-b;
});
//if its sorted
if(num.join(',') === sortedNum.join(',')) {
    //get only unique elems
    var finalArr = $.grep(num, function(el, index) {
        return index === $.inArray(el, num);
    });
    console.log(finalArr);
}
else {
    console.log('Error Not Sorted');
}
FarazShuja
  • 2,287
  • 2
  • 23
  • 34