Check array in JS - is list sorted?

Viewed 19543

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.

9 Answers

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.

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]));

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

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

Sorted Number Lists

Including Negative Numbers, Zeros, and Adjacent Duplicates

Use every() method which will return true should all of the numbers be in order otherwise it will return false. The conditions are as follows:

(num <= arr[idx + 1]) || (idx === arr.length - 1)
  1. if the current number is less than or equal to the next number...

    OR...

  2. if the current index is equal to the last index...

     return 1 (truthy)
    

Demo

var arr0 = [1, 2, 3, 4, 5];
var arr1 = [1, 2, 8, 9, 9];
var arr2 = [1, 2, 2, 3, 2];
var arr3 = [0, 0, 0, 1, 3];
var arr4 = [-3, 0, 1, 3, 3];
var arr5 = [-4, -2, 0, 0, -4];

function sorted(array) {
  return array.every(function(num, idx, arr) {
    return (num <= arr[idx + 1]) || (idx === arr.length - 1) ? 1 : 0;
  });
}

console.log(arr0 +' | '+sorted(arr0));
console.log(arr1 +' | '+sorted(arr1));
console.log(arr2 +' | '+sorted(arr2));
console.log(arr3 +' | '+sorted(arr3));
console.log(arr4 +' | '+sorted(arr4));
console.log(arr5 +' | '+sorted(arr5));

There are plenty of ways how to do that. Here is mine

const isArraySorted = array =>
  array
  .slice(0) // clone array
  .sort((a, b) => a - b) // sort it
  .every((el, i) => el === array[i]) // compare with initial value)

Maybe you can use this helping method that checks if is sorted correctly:

    var arr1 = [1, 2, 3, 4, 4];
    var arr2 = [3, 2, 1];

  console.log(checkList(arr1));
  console.log(checkList(arr2));
    
    function checkList(arr) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i + 1]) {
                if (arr[i] > arr[i + 1]) {
                    return false;
                }
            }

        }
        return true;
    }

You can check if stringified sorted copy of original array has same value as the original one. Might not be the most cool or performant one, but I like it's simplicity and clarity.

const arraysToCheck = [
  [1, 2, 3, 4, 5],
  [1, 2, 8, 9, 9],
  [1, 2, 2, 3, 2]
]

const isSorted = arraysToCheck.map(
  item => JSON.stringify([...item].sort((a, b) => a - b)) === JSON.stringify(item)
 );


console.log(isSorted);

If i get what you mean, you want to know if an array is sorted or not. This is an example of such a solution, try it. I pasted some codes below.

var myArray=[1,4,3,6];

if(isSorted(myArray)){

    console.log("List is sorted");
}else{
    console.log("List is not sorted");
}

function isSorted(X){

var sorted=false;

for(var i=0;i<X.length;i++){

        var next=i+1;

    if (next<=X.length-1){

        if(X[i]>X[next]){
            sorted=false;
            break;
        }else{
            sorted=true;

        }
    }

}


return sorted;

}
Related