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

后端 未结 7 1766
不思量自难忘°
不思量自难忘° 2021-01-18 09:01

I\'m just beginning with programming using javascript and I need to practice some questions to get EXP with the logic of code build. I got this question for homework but I c

7条回答
  •  梦谈多话
    2021-01-18 09:42

    You could use a copy from the second element and check the predecessor for the wanted sort order.

    function checkArray(array) {
        var aa = array.slice(1);
        if (!aa.length) {
            return "Just one element";
        }
        if (aa.every((a, i) => array[i] > a)) {
            return "Ascending";
        }
        if (aa.every((a, i) => array[i] < a)) {
            return "Descending";
        }
        return "Unsorted";
    }
    
    console.log(checkArray([1, 2, 3, 4, 5]));
    console.log(checkArray([5, 4, 3, 2, 1]));
    console.log(checkArray([3, 1, 4, 2, 5]));
    console.log(checkArray([42]));

提交回复
热议问题