Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Js Array Sort in JavaScript

Js Array Sort in JavaScript

? JavaScript Array Sorting


Sorting Arrays in JavaScript

By default, .sort() sorts elements as strings in lexicographical order.


Basic Syntax

array.sort([compareFunction])
  • If no compareFunction is provided, elements are converted to strings and sorted lexicographically.

  • To sort numerically or by custom logic, provide a compareFunction.


Examples

1. Sorting Strings Alphabetically

const fruits = ["banana", "apple", "cherry"];fruits.sort();console.log(fruits); // ["apple", "banana", "cherry"]

2. Sorting Numbers (Ascending)

Default sort without function gives wrong results:

const nums = [10, 5, 100, 1];nums.sort();console.log(nums); // [1, 10, 100, 5]  (wrong for numbers!)

Use a compare function:

nums.sort((a, b) => a - b);console.log(nums); // [1, 5, 10, 100]

3. Sorting Numbers (Descending)

nums.sort((a, b) => b - a);console.log(nums); // [100, 10, 5, 1]

4. Sorting Array of Objects

const people = [  { name: "John", age: 30 },  { name: "Jane", age: 25 },  { name: "Bob", age: 35 }];// Sort by age ascendingpeople.sort((a, b) => a.age - b.age);console.log(people);

How Compare Function Works

The compare function takes two arguments (a, b) and should return:

  • Negative value if a should come before b.

  • Zero if a and b are equal (no change).

  • Positive value if a should come after b.


Summary

UsageExampleResult
Default sort (lexicographic)[3, 10, 1].sort()[1, 10, 3] (unexpected)
Numeric ascending.sort((a,b) => a - b)[1, 3, 10]
Numeric descending.sort((a,b) => b - a)[10, 3, 1]
Sort objects by property.sort((a,b) => a.prop - b.prop)Sorted array of objects by prop

Want me to show stable sorting tricks or locale-aware sorting with localeCompare?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql