Array Is Sorted

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be working with the isSorted function in JavaScript to determine whether a numeric array is sorted in ascending or descending order. We will use the Math.sign() method to convert the final direction value to -1 for descending order and 1 for ascending order. We will also handle cases where the array is empty, has only one element, or the direction changes for any pair of adjacent array elements.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") subgraph Lab Skills javascript/variables -.-> lab-28150{{"`Array Is Sorted`"}} javascript/data_types -.-> lab-28150{{"`Array Is Sorted`"}} javascript/arith_ops -.-> lab-28150{{"`Array Is Sorted`"}} javascript/comp_ops -.-> lab-28150{{"`Array Is Sorted`"}} javascript/cond_stmts -.-> lab-28150{{"`Array Is Sorted`"}} javascript/loops -.-> lab-28150{{"`Array Is Sorted`"}} javascript/array_methods -.-> lab-28150{{"`Array Is Sorted`"}} end

Code Practice: Check if an Array is Sorted

To practice coding, open the Terminal/SSH and type node.

Here's a function to check if a numeric array is sorted:

const isSorted = (arr) => {
  if (arr.length <= 1) return 0;
  const direction = arr[1] - arr[0];
  for (let i = 2; i < arr.length; i++) {
    if ((arr[i] - arr[i - 1]) * direction < 0) return 0;
  }
  return Math.sign(direction);
};

To use it, pass an array of numbers to isSorted(). The function will return 1 if the array is sorted in ascending order, -1 if it's sorted in descending order, and 0 if it's not sorted.

Here are some examples:

isSorted([0, 1, 2, 2]); // 1
isSorted([4, 3, 2]); // -1
isSorted([4, 3, 5]); // 0
isSorted([4]); // 0

Summary

Congratulations! You have completed the Array Is Sorted lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like