DEV Community

Cover image for Array sorting callbacks
Conan
Conan

Posted on • Edited on

1

Array sorting callbacks

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

...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)
Enter fullscreen mode Exit fullscreen mode

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?

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay