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.

4
  • 3
    What did you try so far and what issues have you encountered? Commented Mar 26, 2015 at 18:20
  • And what is your specific problem? Do you know how to iterate over an array? How to compare two values? How to convert a string to a number? Commented Mar 26, 2015 at 18:26
  • technically you have an array of strings. Commented Mar 26, 2015 at 18:35
  • is it possible to check this for var dates = ["mar 1", "mar 2", "mar 2", "mar 3", "mar 4", "mar 4", "mar 5"]; ? Commented Mar 27, 2015 at 13:20

3 Answers 3

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

@halex didn't notice it was strings, fixed
Number would be more appropriate than parseFloat.
@FelixKling not a big difference, but changed (stackoverflow.com/questions/11988547/…)
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');
}

Comments

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;
}

1 Comment

You could replace break with return false, and replace return (i == nPairs) with return true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.