Learn JavaScript
  • Introduction
  • Basics
    • Comments
    • Variables
    • Types
    • Equality
  • Numbers
    • Math
    • Basic Operators
    • Advanced Operators
  • Strings
    • Creation
    • Replace
    • Length
    • Concatenation
  • Conditional Logic
    • If
    • Else
    • Switch
    • Comparators
    • Concatenate
  • Arrays
    • Unshift
    • Map
    • Spread
    • Shift
    • Pop
    • Join
    • Length
    • Push
    • For Each
    • Sort
    • Indices
  • Loops
    • For
    • While
    • Do...While
  • Functions
    • Higher Order Functions
  • Objects
    • Properties
    • Mutable
    • Reference
    • Prototype
    • Delete
    • Enumeration
    • Global footprint
  • Linked List
    • Add
    • Pop
    • Prepend
    • Shift
  • Browser Object Model (BOM)
    • Window
    • Popup
    • Screen
    • Navigator
    • Cookies
    • History
    • Location
  • Date and Time
  • JSON
  • Error Handling
    • try...catch...finally
  • Events
  • Regular Expression
  • Modules
  • Debugging
  • Classes
    • Static
    • Inheritance
    • Access Modifiers
  • Promise, async/await
    • Async/Await
  • Miscellaneous
    • Hoisting
    • Currying
    • Polyfills and Transpilers
  • Exercises
    • Console
    • Multiplication
    • User Input Variables
    • Constants
    • Concatenation
    • Functions
    • Conditional Statements
    • Objects
    • FizzBuzz Problem
    • Get the Titles!
Powered by GitBook
On this page

Was this helpful?

  1. Arrays

Sort

The sort method sorts the items of an array in a specific order (ascending or descending).

let city = ["California", "Barcelona", "Paris", "Kathmandu"];
let sortedCity = city.sort(); 

console.log(sortedCity);

// Result: ['Barcelona', 'California', 'Kathmandu', 'Paris']

Numbers can be sorted incorrectly when they are sorted. For example, "35" is bigger than "100", because "3" is bigger than "1".

To fix the sorting issue in numbers, compare functions are used. Compare functions defines ort orders and return a negative, zero, or positive value based on the arguments.

const points = [40, 100, 1, 5, 25, 10];
points.sort((a, b) => {return a-b});

// Result: [1, 5, 10, 25, 40, 100]

The sort() method overrides the original array.

PreviousFor EachNextIndices

Last updated 2 years ago

Was this helpful?