Loading topic
Array.prototype.sort() with no arguments is one of the most misread methods in JavaScript. It looks like it should "just sort," and with lowercase English words it often seems to. Call it on numbers, dates, mixed-case strings, or arrays with gaps, though, and the results look random until you unde7 min readsort() with no arguments converts every element to a string and orders the results by UTF-16 code units. This chapter covers the fix: passing a comparator function that tells sort() how two elements relate. You will learn the contract a comparator must follow6 min read(a, b) that returns a negative number, zero, or a positive number. It also assumes you know the difference between changing a value in place and creating a new one. Here you will learn why sort() changing its ar7 min readsort (mutates the array) and toSorted (returns a new one). The examples use toSorted, so run them in Node.js 20 or later, or in a current browser. If your e7 min read||, and the difference between sort and toSorted. Here the focus is strings meant for people to read: names, titles, file names, and pro7 min readArray.prototype.sort behaves by default, how to write a comparator that returns a negative, zero, or positive number, and how toSorted differs from sort. Earlier chapters covered all three. You should also know that a typed array is a fixed-length, arr7 min readindexOf, lastIndexOf, and includes. They look alike, but t7 min readindexOf, lastIndexOf, and includes covered searching for a known value. Real searches are usually less exact. You want "the first paid order", "any user without an email", or "every product under $20". Those questions are conditions, not values. JavaScript answers them w6 min readindexOf and find scan an array from one end, and you are comfortable with while loops and integer index arithmetic.7 min readindexOf, includes, find and their relatives) and binary search on a sorted array. This chapter is about choosing between them. On a ten-element array the choice barely matters. On a hundred thousand elements searched thousands of times,7 min read