Check array in JS - is list sorted? [duplicate]












13















This question already has an answer here:




  • Check if an array is descending, ascending or not sorted?

    6 answers



  • Check if array values are ascending or descending

    1 answer




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.










share|improve this question















marked as duplicate by Barmar arrays
Users with the  arrays badge can single-handedly close arrays questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Dec 18 at 17:54


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.




















    13















    This question already has an answer here:




    • Check if an array is descending, ascending or not sorted?

      6 answers



    • Check if array values are ascending or descending

      1 answer




    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.










    share|improve this question















    marked as duplicate by Barmar arrays
    Users with the  arrays badge can single-handedly close arrays questions as duplicates and reopen them as needed.

    StackExchange.ready(function() {
    if (StackExchange.options.isMobile) return;

    $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
    var $hover = $(this).addClass('hover-bound'),
    $msg = $hover.siblings('.dupe-hammer-message');

    $hover.hover(
    function() {
    $hover.showInfoMessage('', {
    messageElement: $msg.clone().show(),
    transient: false,
    position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
    dismissable: false,
    relativeToBody: true
    });
    },
    function() {
    StackExchange.helpers.removeMessages();
    }
    );
    });
    });
    Dec 18 at 17:54


    This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


















      13












      13








      13


      3






      This question already has an answer here:




      • Check if an array is descending, ascending or not sorted?

        6 answers



      • Check if array values are ascending or descending

        1 answer




      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.










      share|improve this question
















      This question already has an answer here:




      • Check if an array is descending, ascending or not sorted?

        6 answers



      • Check if array values are ascending or descending

        1 answer




      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.





      This question already has an answer here:




      • Check if an array is descending, ascending or not sorted?

        6 answers



      • Check if array values are ascending or descending

        1 answer








      javascript arrays sorting






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 18 at 12:51









      MrO

      7451829




      7451829










      asked Dec 18 at 12:35









      Николай Матев

      1009




      1009




      marked as duplicate by Barmar arrays
      Users with the  arrays badge can single-handedly close arrays questions as duplicates and reopen them as needed.

      StackExchange.ready(function() {
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function() {
      $hover.showInfoMessage('', {
      messageElement: $msg.clone().show(),
      transient: false,
      position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
      dismissable: false,
      relativeToBody: true
      });
      },
      function() {
      StackExchange.helpers.removeMessages();
      }
      );
      });
      });
      Dec 18 at 17:54


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






      marked as duplicate by Barmar arrays
      Users with the  arrays badge can single-handedly close arrays questions as duplicates and reopen them as needed.

      StackExchange.ready(function() {
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function() {
      $hover.showInfoMessage('', {
      messageElement: $msg.clone().show(),
      transient: false,
      position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
      dismissable: false,
      relativeToBody: true
      });
      },
      function() {
      StackExchange.helpers.removeMessages();
      }
      );
      });
      });
      Dec 18 at 17:54


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


























          9 Answers
          9






          active

          oldest

          votes


















          5

















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








          share|improve this answer























          • This is really easy, but did you know how to create my Array like your (str): pastebin.com/tBFd9Uft Edit: I get it, only need gets() without .split()
            – Николай Матев
            Dec 18 at 12:58





















          14














          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.






          share|improve this answer



















          • 6




            That's a clever one, though it would be worth to give the user an explanation, unexperienced programmers would never understand what's happening here. For sake of testing, here is a fiddle: jsfiddle.net/briosheje/46r1jm03
            – briosheje
            Dec 18 at 12:48








          • 4




            Indeed. [0, 1, 2, 3, 4, 5] will return false.
            – VisioN
            Dec 18 at 12:52






          • 2




            @VisioN This is a very good point indeed.
            – Stuart
            Dec 18 at 12:53






          • 1




            @KunalMukherjee Correct. That will be an exercise of OP though eh... :)
            – Stuart
            Dec 18 at 12:59






          • 2




            Will this short circuit?
            – Bob Brinks
            Dec 18 at 15:17



















          13














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








          share|improve this answer



















          • 1




            Make it shorter: arr.every((v,i,a) => !i || a[i-1] <= v)
            – VisioN
            Dec 18 at 13:08










          • @VisioN Updated the solution. Thanks for the input.
            – Hassan Imam
            Dec 18 at 13:09












          • Is it really good practice to use tricks like !i for i<1? Otherwise, probably the right way to do this.
            – JollyJoker
            Dec 18 at 14:12






          • 1




            @JollyJoker I wouldn't call it a trick--it's equivalent to i === 0 (which might be more readable). This is the best solution on the thread because it combines early bailout with modern, functional syntax.
            – ggorlen
            Dec 18 at 16:10












          • @ggorlen Some things are standard in Javascript that would be considered oddities to avoid in other languages
            – JollyJoker
            Dec 20 at 8:15



















          8















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








          share|improve this answer



















          • 3




            This is very neat and tidy, have an upvote :)
            – Stuart
            Dec 18 at 13:04



















          3














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








          share|improve this answer























          • for [0, 1, 3, 4, 5] it returns false
            – Luca Rainone
            Dec 18 at 13:28










          • See update, thanks @LucaRainone
            – zer00ne
            Dec 18 at 13:43










          • The point is that the trick is dangerous. For example it does not works with negative numbers. [-2, 0, 3, 4, 5]. But also your solution does not work for [0, 0, 1, 4, 5]
            – Luca Rainone
            Dec 18 at 13:49










          • The callback for every gets value, index and the array. Aren't you comparing value to index?
            – JollyJoker
            Dec 18 at 14:11










          • See update, thanks @LucaRainone
            – zer00ne
            Dec 18 at 18:00



















          0














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








          share|improve this answer





























            0














            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)








            share|improve this answer





























              0














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








              share|improve this answer































                -1














                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;

                }





                share|improve this answer




























                  9 Answers
                  9






                  active

                  oldest

                  votes








                  9 Answers
                  9






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  5

















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








                  share|improve this answer























                  • This is really easy, but did you know how to create my Array like your (str): pastebin.com/tBFd9Uft Edit: I get it, only need gets() without .split()
                    – Николай Матев
                    Dec 18 at 12:58


















                  5

















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








                  share|improve this answer























                  • This is really easy, but did you know how to create my Array like your (str): pastebin.com/tBFd9Uft Edit: I get it, only need gets() without .split()
                    – Николай Матев
                    Dec 18 at 12:58
















                  5












                  5








                  5









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








                  share|improve this answer

















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








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





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






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Dec 18 at 17:09









                  Community

                  11




                  11










                  answered Dec 18 at 12:43









                  Jin

                  926221




                  926221












                  • This is really easy, but did you know how to create my Array like your (str): pastebin.com/tBFd9Uft Edit: I get it, only need gets() without .split()
                    – Николай Матев
                    Dec 18 at 12:58




















                  • This is really easy, but did you know how to create my Array like your (str): pastebin.com/tBFd9Uft Edit: I get it, only need gets() without .split()
                    – Николай Матев
                    Dec 18 at 12:58


















                  This is really easy, but did you know how to create my Array like your (str): pastebin.com/tBFd9Uft Edit: I get it, only need gets() without .split()
                  – Николай Матев
                  Dec 18 at 12:58






                  This is really easy, but did you know how to create my Array like your (str): pastebin.com/tBFd9Uft Edit: I get it, only need gets() without .split()
                  – Николай Матев
                  Dec 18 at 12:58















                  14














                  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.






                  share|improve this answer



















                  • 6




                    That's a clever one, though it would be worth to give the user an explanation, unexperienced programmers would never understand what's happening here. For sake of testing, here is a fiddle: jsfiddle.net/briosheje/46r1jm03
                    – briosheje
                    Dec 18 at 12:48








                  • 4




                    Indeed. [0, 1, 2, 3, 4, 5] will return false.
                    – VisioN
                    Dec 18 at 12:52






                  • 2




                    @VisioN This is a very good point indeed.
                    – Stuart
                    Dec 18 at 12:53






                  • 1




                    @KunalMukherjee Correct. That will be an exercise of OP though eh... :)
                    – Stuart
                    Dec 18 at 12:59






                  • 2




                    Will this short circuit?
                    – Bob Brinks
                    Dec 18 at 15:17
















                  14














                  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.






                  share|improve this answer



















                  • 6




                    That's a clever one, though it would be worth to give the user an explanation, unexperienced programmers would never understand what's happening here. For sake of testing, here is a fiddle: jsfiddle.net/briosheje/46r1jm03
                    – briosheje
                    Dec 18 at 12:48








                  • 4




                    Indeed. [0, 1, 2, 3, 4, 5] will return false.
                    – VisioN
                    Dec 18 at 12:52






                  • 2




                    @VisioN This is a very good point indeed.
                    – Stuart
                    Dec 18 at 12:53






                  • 1




                    @KunalMukherjee Correct. That will be an exercise of OP though eh... :)
                    – Stuart
                    Dec 18 at 12:59






                  • 2




                    Will this short circuit?
                    – Bob Brinks
                    Dec 18 at 15:17














                  14












                  14








                  14






                  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.






                  share|improve this answer














                  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.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Dec 18 at 14:21









                  Tim Castelijns

                  30.8k1286109




                  30.8k1286109










                  answered Dec 18 at 12:46









                  Stuart

                  5,13921429




                  5,13921429








                  • 6




                    That's a clever one, though it would be worth to give the user an explanation, unexperienced programmers would never understand what's happening here. For sake of testing, here is a fiddle: jsfiddle.net/briosheje/46r1jm03
                    – briosheje
                    Dec 18 at 12:48








                  • 4




                    Indeed. [0, 1, 2, 3, 4, 5] will return false.
                    – VisioN
                    Dec 18 at 12:52






                  • 2




                    @VisioN This is a very good point indeed.
                    – Stuart
                    Dec 18 at 12:53






                  • 1




                    @KunalMukherjee Correct. That will be an exercise of OP though eh... :)
                    – Stuart
                    Dec 18 at 12:59






                  • 2




                    Will this short circuit?
                    – Bob Brinks
                    Dec 18 at 15:17














                  • 6




                    That's a clever one, though it would be worth to give the user an explanation, unexperienced programmers would never understand what's happening here. For sake of testing, here is a fiddle: jsfiddle.net/briosheje/46r1jm03
                    – briosheje
                    Dec 18 at 12:48








                  • 4




                    Indeed. [0, 1, 2, 3, 4, 5] will return false.
                    – VisioN
                    Dec 18 at 12:52






                  • 2




                    @VisioN This is a very good point indeed.
                    – Stuart
                    Dec 18 at 12:53






                  • 1




                    @KunalMukherjee Correct. That will be an exercise of OP though eh... :)
                    – Stuart
                    Dec 18 at 12:59






                  • 2




                    Will this short circuit?
                    – Bob Brinks
                    Dec 18 at 15:17








                  6




                  6




                  That's a clever one, though it would be worth to give the user an explanation, unexperienced programmers would never understand what's happening here. For sake of testing, here is a fiddle: jsfiddle.net/briosheje/46r1jm03
                  – briosheje
                  Dec 18 at 12:48






                  That's a clever one, though it would be worth to give the user an explanation, unexperienced programmers would never understand what's happening here. For sake of testing, here is a fiddle: jsfiddle.net/briosheje/46r1jm03
                  – briosheje
                  Dec 18 at 12:48






                  4




                  4




                  Indeed. [0, 1, 2, 3, 4, 5] will return false.
                  – VisioN
                  Dec 18 at 12:52




                  Indeed. [0, 1, 2, 3, 4, 5] will return false.
                  – VisioN
                  Dec 18 at 12:52




                  2




                  2




                  @VisioN This is a very good point indeed.
                  – Stuart
                  Dec 18 at 12:53




                  @VisioN This is a very good point indeed.
                  – Stuart
                  Dec 18 at 12:53




                  1




                  1




                  @KunalMukherjee Correct. That will be an exercise of OP though eh... :)
                  – Stuart
                  Dec 18 at 12:59




                  @KunalMukherjee Correct. That will be an exercise of OP though eh... :)
                  – Stuart
                  Dec 18 at 12:59




                  2




                  2




                  Will this short circuit?
                  – Bob Brinks
                  Dec 18 at 15:17




                  Will this short circuit?
                  – Bob Brinks
                  Dec 18 at 15:17











                  13














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








                  share|improve this answer



















                  • 1




                    Make it shorter: arr.every((v,i,a) => !i || a[i-1] <= v)
                    – VisioN
                    Dec 18 at 13:08










                  • @VisioN Updated the solution. Thanks for the input.
                    – Hassan Imam
                    Dec 18 at 13:09












                  • Is it really good practice to use tricks like !i for i<1? Otherwise, probably the right way to do this.
                    – JollyJoker
                    Dec 18 at 14:12






                  • 1




                    @JollyJoker I wouldn't call it a trick--it's equivalent to i === 0 (which might be more readable). This is the best solution on the thread because it combines early bailout with modern, functional syntax.
                    – ggorlen
                    Dec 18 at 16:10












                  • @ggorlen Some things are standard in Javascript that would be considered oddities to avoid in other languages
                    – JollyJoker
                    Dec 20 at 8:15
















                  13














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








                  share|improve this answer



















                  • 1




                    Make it shorter: arr.every((v,i,a) => !i || a[i-1] <= v)
                    – VisioN
                    Dec 18 at 13:08










                  • @VisioN Updated the solution. Thanks for the input.
                    – Hassan Imam
                    Dec 18 at 13:09












                  • Is it really good practice to use tricks like !i for i<1? Otherwise, probably the right way to do this.
                    – JollyJoker
                    Dec 18 at 14:12






                  • 1




                    @JollyJoker I wouldn't call it a trick--it's equivalent to i === 0 (which might be more readable). This is the best solution on the thread because it combines early bailout with modern, functional syntax.
                    – ggorlen
                    Dec 18 at 16:10












                  • @ggorlen Some things are standard in Javascript that would be considered oddities to avoid in other languages
                    – JollyJoker
                    Dec 20 at 8:15














                  13












                  13








                  13






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








                  share|improve this answer














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








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





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






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Dec 18 at 13:09

























                  answered Dec 18 at 13:01









                  Hassan Imam

                  11.9k31230




                  11.9k31230








                  • 1




                    Make it shorter: arr.every((v,i,a) => !i || a[i-1] <= v)
                    – VisioN
                    Dec 18 at 13:08










                  • @VisioN Updated the solution. Thanks for the input.
                    – Hassan Imam
                    Dec 18 at 13:09












                  • Is it really good practice to use tricks like !i for i<1? Otherwise, probably the right way to do this.
                    – JollyJoker
                    Dec 18 at 14:12






                  • 1




                    @JollyJoker I wouldn't call it a trick--it's equivalent to i === 0 (which might be more readable). This is the best solution on the thread because it combines early bailout with modern, functional syntax.
                    – ggorlen
                    Dec 18 at 16:10












                  • @ggorlen Some things are standard in Javascript that would be considered oddities to avoid in other languages
                    – JollyJoker
                    Dec 20 at 8:15














                  • 1




                    Make it shorter: arr.every((v,i,a) => !i || a[i-1] <= v)
                    – VisioN
                    Dec 18 at 13:08










                  • @VisioN Updated the solution. Thanks for the input.
                    – Hassan Imam
                    Dec 18 at 13:09












                  • Is it really good practice to use tricks like !i for i<1? Otherwise, probably the right way to do this.
                    – JollyJoker
                    Dec 18 at 14:12






                  • 1




                    @JollyJoker I wouldn't call it a trick--it's equivalent to i === 0 (which might be more readable). This is the best solution on the thread because it combines early bailout with modern, functional syntax.
                    – ggorlen
                    Dec 18 at 16:10












                  • @ggorlen Some things are standard in Javascript that would be considered oddities to avoid in other languages
                    – JollyJoker
                    Dec 20 at 8:15








                  1




                  1




                  Make it shorter: arr.every((v,i,a) => !i || a[i-1] <= v)
                  – VisioN
                  Dec 18 at 13:08




                  Make it shorter: arr.every((v,i,a) => !i || a[i-1] <= v)
                  – VisioN
                  Dec 18 at 13:08












                  @VisioN Updated the solution. Thanks for the input.
                  – Hassan Imam
                  Dec 18 at 13:09






                  @VisioN Updated the solution. Thanks for the input.
                  – Hassan Imam
                  Dec 18 at 13:09














                  Is it really good practice to use tricks like !i for i<1? Otherwise, probably the right way to do this.
                  – JollyJoker
                  Dec 18 at 14:12




                  Is it really good practice to use tricks like !i for i<1? Otherwise, probably the right way to do this.
                  – JollyJoker
                  Dec 18 at 14:12




                  1




                  1




                  @JollyJoker I wouldn't call it a trick--it's equivalent to i === 0 (which might be more readable). This is the best solution on the thread because it combines early bailout with modern, functional syntax.
                  – ggorlen
                  Dec 18 at 16:10






                  @JollyJoker I wouldn't call it a trick--it's equivalent to i === 0 (which might be more readable). This is the best solution on the thread because it combines early bailout with modern, functional syntax.
                  – ggorlen
                  Dec 18 at 16:10














                  @ggorlen Some things are standard in Javascript that would be considered oddities to avoid in other languages
                  – JollyJoker
                  Dec 20 at 8:15




                  @ggorlen Some things are standard in Javascript that would be considered oddities to avoid in other languages
                  – JollyJoker
                  Dec 20 at 8:15











                  8















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








                  share|improve this answer



















                  • 3




                    This is very neat and tidy, have an upvote :)
                    – Stuart
                    Dec 18 at 13:04
















                  8















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








                  share|improve this answer



















                  • 3




                    This is very neat and tidy, have an upvote :)
                    – Stuart
                    Dec 18 at 13:04














                  8












                  8








                  8







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








                  share|improve this answer















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






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Dec 18 at 13:27









                  Vikas Prabhu

                  449




                  449










                  answered Dec 18 at 12:54









                  Ramesh Rajendran

                  18.4k1982147




                  18.4k1982147








                  • 3




                    This is very neat and tidy, have an upvote :)
                    – Stuart
                    Dec 18 at 13:04














                  • 3




                    This is very neat and tidy, have an upvote :)
                    – Stuart
                    Dec 18 at 13:04








                  3




                  3




                  This is very neat and tidy, have an upvote :)
                  – Stuart
                  Dec 18 at 13:04




                  This is very neat and tidy, have an upvote :)
                  – Stuart
                  Dec 18 at 13:04











                  3














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








                  share|improve this answer























                  • for [0, 1, 3, 4, 5] it returns false
                    – Luca Rainone
                    Dec 18 at 13:28










                  • See update, thanks @LucaRainone
                    – zer00ne
                    Dec 18 at 13:43










                  • The point is that the trick is dangerous. For example it does not works with negative numbers. [-2, 0, 3, 4, 5]. But also your solution does not work for [0, 0, 1, 4, 5]
                    – Luca Rainone
                    Dec 18 at 13:49










                  • The callback for every gets value, index and the array. Aren't you comparing value to index?
                    – JollyJoker
                    Dec 18 at 14:11










                  • See update, thanks @LucaRainone
                    – zer00ne
                    Dec 18 at 18:00
















                  3














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








                  share|improve this answer























                  • for [0, 1, 3, 4, 5] it returns false
                    – Luca Rainone
                    Dec 18 at 13:28










                  • See update, thanks @LucaRainone
                    – zer00ne
                    Dec 18 at 13:43










                  • The point is that the trick is dangerous. For example it does not works with negative numbers. [-2, 0, 3, 4, 5]. But also your solution does not work for [0, 0, 1, 4, 5]
                    – Luca Rainone
                    Dec 18 at 13:49










                  • The callback for every gets value, index and the array. Aren't you comparing value to index?
                    – JollyJoker
                    Dec 18 at 14:11










                  • See update, thanks @LucaRainone
                    – zer00ne
                    Dec 18 at 18:00














                  3












                  3








                  3






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








                  share|improve this answer














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








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





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






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Dec 18 at 17:59

























                  answered Dec 18 at 13:19









                  zer00ne

                  23.1k32241




                  23.1k32241












                  • for [0, 1, 3, 4, 5] it returns false
                    – Luca Rainone
                    Dec 18 at 13:28










                  • See update, thanks @LucaRainone
                    – zer00ne
                    Dec 18 at 13:43










                  • The point is that the trick is dangerous. For example it does not works with negative numbers. [-2, 0, 3, 4, 5]. But also your solution does not work for [0, 0, 1, 4, 5]
                    – Luca Rainone
                    Dec 18 at 13:49










                  • The callback for every gets value, index and the array. Aren't you comparing value to index?
                    – JollyJoker
                    Dec 18 at 14:11










                  • See update, thanks @LucaRainone
                    – zer00ne
                    Dec 18 at 18:00


















                  • for [0, 1, 3, 4, 5] it returns false
                    – Luca Rainone
                    Dec 18 at 13:28










                  • See update, thanks @LucaRainone
                    – zer00ne
                    Dec 18 at 13:43










                  • The point is that the trick is dangerous. For example it does not works with negative numbers. [-2, 0, 3, 4, 5]. But also your solution does not work for [0, 0, 1, 4, 5]
                    – Luca Rainone
                    Dec 18 at 13:49










                  • The callback for every gets value, index and the array. Aren't you comparing value to index?
                    – JollyJoker
                    Dec 18 at 14:11










                  • See update, thanks @LucaRainone
                    – zer00ne
                    Dec 18 at 18:00
















                  for [0, 1, 3, 4, 5] it returns false
                  – Luca Rainone
                  Dec 18 at 13:28




                  for [0, 1, 3, 4, 5] it returns false
                  – Luca Rainone
                  Dec 18 at 13:28












                  See update, thanks @LucaRainone
                  – zer00ne
                  Dec 18 at 13:43




                  See update, thanks @LucaRainone
                  – zer00ne
                  Dec 18 at 13:43












                  The point is that the trick is dangerous. For example it does not works with negative numbers. [-2, 0, 3, 4, 5]. But also your solution does not work for [0, 0, 1, 4, 5]
                  – Luca Rainone
                  Dec 18 at 13:49




                  The point is that the trick is dangerous. For example it does not works with negative numbers. [-2, 0, 3, 4, 5]. But also your solution does not work for [0, 0, 1, 4, 5]
                  – Luca Rainone
                  Dec 18 at 13:49












                  The callback for every gets value, index and the array. Aren't you comparing value to index?
                  – JollyJoker
                  Dec 18 at 14:11




                  The callback for every gets value, index and the array. Aren't you comparing value to index?
                  – JollyJoker
                  Dec 18 at 14:11












                  See update, thanks @LucaRainone
                  – zer00ne
                  Dec 18 at 18:00




                  See update, thanks @LucaRainone
                  – zer00ne
                  Dec 18 at 18:00











                  0














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








                  share|improve this answer


























                    0














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








                    share|improve this answer
























                      0












                      0








                      0






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








                      share|improve this answer












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








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





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






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Dec 18 at 12:49









                      André

                      31318




                      31318























                          0














                          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)








                          share|improve this answer


























                            0














                            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)








                            share|improve this answer
























                              0












                              0








                              0






                              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)








                              share|improve this answer












                              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)








                              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)





                              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)






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Dec 18 at 12:58









                              Dima Vishnyakov

                              18917




                              18917























                                  0














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








                                  share|improve this answer




























                                    0














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








                                    share|improve this answer


























                                      0












                                      0








                                      0






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








                                      share|improve this answer














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








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





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






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Dec 18 at 14:58

























                                      answered Dec 18 at 13:14









                                      HynekS

                                      460414




                                      460414























                                          -1














                                          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;

                                          }





                                          share|improve this answer


























                                            -1














                                            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;

                                            }





                                            share|improve this answer
























                                              -1












                                              -1








                                              -1






                                              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;

                                              }





                                              share|improve this answer












                                              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;

                                              }






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Dec 18 at 12:56









                                              prog-etien.io

                                              46




                                              46















                                                  Popular posts from this blog

                                                  Morgemoulin

                                                  Scott Moir

                                                  Souastre