Sorting words using the sort() method

You’ve been given an array of words and asked to sort them in alphabetical order.

const words = ['red', 'yellow', 'green']
words.sort()

console.log(words) // 'green', 'red', 'yellow']

Wow, that was easy!

Here’s how it works:

The sort() method is used to rearrange the elements of an array in ascending order by default. However, the default sorting behavior is based on converting elements to strings and comparing their UTF-16 code unit values. In UTF-16, each character is represented by a code unit, which is a 16-bit binary number.

Here are the UTF-16 code unit values for the lowercase English alphabet characters:

‘g’ – 103

‘y’ – 121

‘r’ – 114

These values represent the order of characters as per their ASCII values. When using the sort() method, it compares the UTF-16 code unit values, which is why ‘green’ comes before ‘red’ and ‘yellow’ in the sorted result.

Beware when sorting lowercase and uppercase words or letters.

const colors = ['red', 'Yellow', 'green']
colors.sort()

console.log(colors) // result: ["Yellow", "green", "red"]

Why didn’t this work?

Sorting is case-sensitive, and uppercase letters will be sorted before lowercase letters. That’s because uppercase letters have lower Unicode code points than lowercase letters.

Here are the UTF-16 code unit values for the uppercase English alphabet characters:

‘g’ – 103

‘Y’ – 89

‘r’ – 114

That’s why 'Yellow' comes before 'green' and 'red' in the sorted result. So if you directly use sort() on an array of strings, it might not always give you the expected result!

To avoid this from happening, use a custom function instead!

const colors = ['red', 'Yellow', 'green']
colors.sort(function(a,b) {
    return a.toLowerCase() < b.toLowerCase() ? -1 : 1
})

console.log(colors)  // result: [green, red, Yellow]

The comparison function takes two parameters, a and b, which represent two elements being compared.

  • a.toLowerCase() and b.toLowerCase() convert the strings a and b to lowercase, ensuring a case-insensitive comparison.

The comparison is based on the result of comparing the lowercase versions of a and b. Here’s how it works:

  • If a (in lowercase) is less than b (in lowercase), the ternary conditional returns -1, indicating that a should come before b in the sorted array.
  • Otherwise, if a (in lowercase) is greater than or equal to b (in lowercase), the ternary conditional returns 1, indicating that a should come after b in the sorted array.

Let’s refactor!

const colors = ['red', 'Yellow', 'green']
colors.sort((a,b) => a.toLowerCase() < b.toLowerCase() ? -1 : 1)

console.log(colors) results: ['green', 'red', 'Yellow']

We can refactor again using the localeCompare() method!

The localeCompare() method in JavaScript is a built-in string method used to compare two strings based on their linguistic and natural language rules. It provides a way to perform string comparisons that take into account various language-specific considerations, including case sensitivity!

Here’s the refactored code using localeCompare():

const colors = ['red', 'Yellow', 'green']
const compare = (a, b) => a.toLowerCase().localeCompare(b.toLowerCase())

colors.sort(compare)
console.log(colors) results: ['green', 'red', 'Yellow']

Remember: the sort() method modifies
the original array!

Sorting numbers with the sort() method

You’ve been given an array of numbers and asked to sort them in ascending order. Let’s take a look…

const numbers = [9, 10, 4]
numbers.sort()

console.log(numbers) // result: [10, 4, 9]

Well, that’s not right!

Here’s why:

The default behavior of the sort() method in JavaScript is to convert elements to strings before performing comparisons. This can sometimes lead to unexpected results when sorting numbers.

Instead, you’ll need to use a comparison function that explicitly compares numbers like this:

const numbers = [9, 10, 4]
numbers.sort((a, b) => a - b)

console.log(numbers) // [4, 9, 10]

How does the compare function work?

It takes two arguments (usually named a and b), representing two elements being compared. It should return a negative value if a should be sorted before b, a positive value if a should be sorted after b, and zero if the order of a and b doesn’t matter.

Let’s explain:
Sort 1: [9, 10, 4], where a = 9 and b = 10. Since 9 – 10 = -1, a should be sorted before b: 9 is sorted before 10, there’s no change. [9, 10, 4]

Sort 2: [9, 10, 4], where a = 10 and b = 4. Since 10 – 4 = 6, a should be sorted after b: 10 is sorted after 4. [9, 4, 10]

Sort 3: [9, 4, 10], where a = 9 and b = 4. Since 9 – 4 = 5, a should be sorted after b: 9 should be sorted after 4. [4, 9, 10]

FYI: the sort() method modifies
the original array!

To avoid this from happening, use the slice() method to create a shallow copy:

Below, the slice() method is called on originalArray with no arguments. This creates a new array that is a shallow copy of originalArray. The purpose of using slice() in this context is to prevent the sort() method from directly modifying the originalArray. Since sort() sorts arrays in place and modifies the original array, creating a shallow copy using slice() ensures that the original array remains unchanged while you work with the sorted version!

const originalArray = [9, 10, 4]
const sortedArray = originalArray.slice().sort((a,b) => a-b)

console.log(originalArray) // result: [9, 10, 4]
console.log(sortedArray) // result: [4, 9, 10]

Using Hershey’s Kisses with a Raspberry Pi and Python

Wire up a button (in this case, two Hershey’s Kisses) and an LED to the Raspberry Pi and write some code to respond to the Hershey’s Kisses when they touch each other. On contact, the LED will light and “on” will be printed in the Python shell. Here’s the Python code:

from gpiozero import LED, Button
from time import time, sleep
led = LED(27)
btn = Button(17)
 
while True:
    led.off()
    print('off')
    sleep(.5)
    btn.wait_for_press()
    led.on()
    print('on')
    sleep(.5)

Learn how to program with Raspberry Pi

The Raspberry Pi is a low cost, credit-card sized computer that plugs into a computer monitor or TV, and uses a standard keyboard and mouse. It is a capable little device that enables people of all ages to explore computing, and to learn how to program in languages like Scratch and Python. It’s capable of doing everything you’d expect a desktop computer to do, from browsing the internet and playing high-definition video, to making spreadsheets, word-processing, and playing games.

What’s more, the Raspberry Pi  has the ability to interact with the outside world, and has been used in a wide array of digital maker projects, from music machines and parent detectors to weather stations and tweeting birdhouses with infra-red cameras.