Search code examples
javascriptarrayssorting

Check array in JS - is list sorted?


I need to create a program that checks the list in the array is sorted. I have three input data:

1,2,3,4,5

1,2,8,9,9

1,2,2,3,2

So here is my code:

let sorts = +gets(); // 3
let list = [];

for (let i = 0; i < sorts; i++) {
    list[i] = gets().split(',').map(Number); // The Array will be: [ [ 1, 2, 3, 4, 5 ], [ 1, 2, 8, 9, 9 ], [ 1, 2, 2, 3, 2 ] ]
}

for (let i = 0; i < list[i][i].length; i++){
    if (list[i][i] < list[i][i +1]) {
        print('true');
    } else {
        print('false');
    }
}

I need to print for all lists on new line true or false. For this example my output needs to be:

true

true

false

I have no idea how to resolve this.


Solution

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