惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

K
Kaspersky official blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
V
Visual Studio Blog
F
Full Disclosure
B
Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
L
Lohrmann on Cybersecurity
月光博客
月光博客
I
Intezer
博客园 - 三生石上(FineUI控件)
Hacker News - Newest:
Hacker News - Newest: "LLM"
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园_首页
P
Proofpoint News Feed
C
Check Point Blog
N
News | PayPal Newsroom
H
Heimdal Security Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
G
GRAHAM CLULEY
WordPress大学
WordPress大学
C
CERT Recently Published Vulnerability Notes
Y
Y Combinator Blog
Recorded Future
Recorded Future
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Tailwind CSS Blog
W
WeLiveSecurity
L
LINUX DO - 热门话题
Microsoft Azure Blog
Microsoft Azure Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Schneier on Security
Schneier on Security
爱范儿
爱范儿
Martin Fowler
Martin Fowler
U
Unit 42
T
Troy Hunt's Blog
S
Securelist
V
V2EX
V2EX - 技术
V2EX - 技术
MongoDB | Blog
MongoDB | Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
M
MIT News - Artificial intelligence
T
Tor Project blog
Cisco Talos Blog
Cisco Talos Blog
罗磊的独立博客
小众软件
小众软件
阮一峰的网络日志
阮一峰的网络日志
Vercel News
Vercel News

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
array.sort() Does Not Simply Sort Numbers in JavaScript
Dmitri Pavlutin · 2021-01-26 · via Dmitri Pavlutin Blog

In JavaScript, the array.sort() method sorts the array. Let's use it to sort some numbers:


const numbers = [10, 5, 11];

numbers.sort(); // => [10, 11, 5]


Hm... numbers.sort() returns [10, 11, 5] — which doesn't look like a sorted array in ascrending order.

Why does array.sort() method, when invoked without arguments, doesn't sort the numbers as expected? Let's find the answer.

1. array.sort() without arguments

array.sort() is a method on array instance that sorts the array in place (mutates the original array) and returns the sorted array.

When called without arguments, the array items are transformed to strings and sorted... alphabetically.

For example, let's sort an array of names:


const names = ['joker', 'batman', 'catwoman'];

names.sort(); // => ['batman', 'catwoman', 'joker']


The names are sorted alphabetically: ['batman', 'catwoman', 'joker'].

Unfortunately, invoking the method on numbers performs the same alphabetical sorting:


const numbers = [10, 5, 11];

numbers.sort(); // => [10, 11, 5]


The method returns the array [10, 11, 5] having numbers sorted alphabetically, rather than by their numeric value.

2. array.sort() with a comparator

Fortunately, array.sort() method accepts an optional argument: the comparator function.


const mutatedArray = array.sort([comparator]);


Using this function you can control how element are ordered in the array during sorting.

If comparator(a, b) returns:

  • A negative number < 0: then a is placed before b
  • A positive number > 0: then b is placed before a
  • Zero 0: then the position of the compared elements doesn't change

To correctly sort numbers in ascending order, let's use the following comparator function:


const numbers = [10, 5, 11];

numbers.sort((a, b) => {

if (a < b) {

return -1;

}

if (a > b) {

return 1;

}

return 0;

}); // => [5, 10, 11]


numbers.sort(comparator) now correctly sorts the numbers: [5, 10, 11].

In a sorted in ascrending order array the smaller number is positioned before a bigger one. That's the property you need to maintain when coding the comparator function:

  • If a < b — the function returns -1, placing a before b (e.g. 5 < 8, thus 5 is before 8)
  • If a > b — the function returns 1, placing b before a (e.g. 10 > 3, thus 3 is before 10)
  • If a === b — order is not changed.

The comparator function in the previous example is relatively long. Fortunately, it can be simplified by just diffing the arguments:


const numbers = [10, 5, 11];

numbers.sort((a, b) => a - b); // => [5, 10, 11]


(a, b) => a - b is a short comparator to sort numbers. I recommend this form to sort the array of numbers in JavaScript.

3. Sorting using a typed array

The typed arrays in JavaScript contain elements of a specific type, e.g. UInt8: 8 bit unsigned integers, Float64: 64 bit floating point numbers. That's in contrast to the regular array, where elements can be of any type, or even mix of types.

The good thing about typed arrays is that their sort() method by default performs an ordering on the numbers in ascending order.

A contrived approach to sort numbers, without using a comparator function, is to make use of a typed array:


const numbers = [10, 5, 11];

const sortedNumbers = [...new Float64Array(numbers).sort()];

sortedNumbers; // => [5, 10, 11]


new Float64Array(numbers) creates an instance of a typed array initiazed with numbers from numbers array.

new Float64Array(numbers).sort() sorts in ascending order the numbers of the typed array. Note that a comparator function isn't needed.

Finally, the spread operator [...new Float64Array(numbers).sort()] extracts the sorted numbers from the typed array into a regular array.

4. Summary

array.sort() method invoked without arguments sorts the elements alphabetically. That's why using array.sort() to sort numbers in ascending order doesn't work.

But you can indicate a comparator function array.sort(comparator) to customize how the elements are sorted. I recommend numbers.sort((a, b) => a - b) as one of the shortest way to sort an array of numbers.

Quiz: how would you sort numbers in a descending order? Write your answer in a comment below!