Photo by Edu Grande on Unsplash
A short Q&A on Array#sort()
and passing a basic callback.
Before starting, let's just shorten console.log
:
const { log } = console
Similar to before, the question is:
"At the end of each run, can you guess what will be logged?" π€
1. array
vs. [...array]
const chars = ['a', 'πͺ΄', 'n', 'Z']
const sort = arr => [...arr].sort()
const sortInPlace = arr => arr.sort()
// 1a)
const output1 = sort()
log('output1 === ', output1)
log('chars === ', chars)
// 1b)
const output2 = sortInPlace()
log('output2 === ', output2)
log('chars === ', chars)
2. numbers vs. strings
const numbers = [2, 3, 1, 10]
const strings = ['2', '3', '1', '10']
const sort = arr => [...arr].sort()
// 2a)
const output1 = sort(numbers)
log('output1 === ', output1)
// 2b)
const output2 = sort(strings)
log('output2 === ', output2)
3. using a callback
If callback
looks like this...
function compare(a, b) {
if (a < b) return -1
if (a === b) return 0
if (a > b) return 1
}
...then:
const numbers = [2, 3, 1, 10]
const sort = () =>
[...numbers].sort()
const sortCompare = () =>
[...numbers].sort(compare)
// 3a)
const output1 = sort()
log('output1 === ', output1)
// 3b)
const output2 = sortCompare()
log('output2 === ', output2)
If you need a little help, I made a corresponding interactive version of the article that offers some very basic visuals (with a few extras toward the bottom!)
I'm not sure if they help intuit what's going on, but they give the answers at least! Did they meet your expectations?
Top comments (0)