Compare two arrays of numbers checking all values are greater than another [duplicate]

Solution 1:

How about something like this:

!![1,2,3,4,5].reduce((n, item) => n !== false && item >= n && item)
// true

!![1,2,8,9,9].reduce((n, item) => n !== false && item >= n && item)
// true 

!![1,2,2,3,2].reduce((n, item) => n !== false && item >= n && item)
// false

Reduce will literally reduce the array down to a single value - a boolean in our case.

Here, we are calling a function per iteration, the (n, item) is our function signature, it's body being n !== false && item >- n && item - we are making sure that n exists (n is our accumulator - read up!), testing if item is greater than n, and making sure item exists.

This happens for every element in your array. We then use !! to force the result into a tru boolean.

Solution 2:

You can use array#every to check if each value is greater than the previous value.

const isSorted = arr => arr.every((v,i,a) => !i || a[i-1] <= v);
console.log(isSorted([1,2,3,4,5]));
console.log(isSorted([1,2,8,9,9])); 
console.log(isSorted([1,2,2,3,2]));

Solution 3:

Simply try this way by using slice method : It will check if previous element is less than the next element.If the condition is true for every element then it will return true else false

arr.slice(1).every((item, i) => arr[i] <= item);

Checkout this below sample as Demo

var arr = [[1,2,3,4,5],[1,2,8,9,9],[1,2,2,3,2],[0,1,2,3,4,5]];

function isArrayIsSorted (arr) {
  return arr.slice(1).every((item, i) => arr[i] <= item)
}

var result= [];
for (var i = 0; i < arr.length; i++){
result.push(isArrayIsSorted(arr[i]))
}
console.log(result);

Solution 4:

var str = ["1,2,3,4,5", "1,2,8,9,9", "1,2,2,3,2"];

for (var i in str){
    var list = str[i].split(',').map(Number);
    console.log(list);
    var isSorted = true;
    for(var j = 0 ; j < list.length - 1 ; j++){
        if(list[j] > list[j+1]) {
            isSorted = false;
            break;
        }
    }
    console.log(isSorted);
}