Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readJavaScript

Sort and edit arrays without mutation

Use toSorted(), toSpliced() and with() to make a shallow copy while preserving the source array and its order.

You sort a list to render it by priority, then another view loses the order it got from the API. Both views hold the same array, and sort() rearranged it in place. Use a copying method when the result belongs to one view.

Sort the view's copy

Pass toSorted() the comparator you would pass to sort(). The comparator below puts the smallest numeric priority first.

const jobs = [
  { id: 'email', priority: 3 },
  { id: 'sync', priority: 1 },
  { id: 'export', priority: 2 },
]

const sorted = jobs.toSorted((a, b) => a.priority - b.priority)

console.log(jobs.map(({ id }) => id).join(', '))
console.log(sorted.map(({ id }) => id).join(', '))

The source order prints as email, sync, export, and the result prints as sync, export, email. Each view can choose which array to read.

Include the comparator when you want numeric order. The default sort compares string forms, so with plain numbers it can put 10 ahead of 2.

Replace a range or one item

Use toSpliced() when the edit changes a run of entries. Use with() when you know the index and want to replace one entry. Both return an array, so assign the result to the state or variable your view uses.

const queue = ['email', 'sync', 'export']

console.log(queue.toSpliced(1, 1, 'backup', 'retry'))
console.log(queue.with(-1, 'archive'))
console.log(queue)

The first array contains backup and retry where sync was. The second ends in archive, and the third shows the source queue in its original order.

The return value is easy to miss when migrating calls. splice() returns the removed items. toSpliced() returns the edited array. With with(), a negative index counts from the end and an out-of-range index throws a RangeError. Check the result of findIndex() before passing it in, since a failed lookup returns -1 and would replace the last item.

Copy the object you change

These copying array methods keep the original object references. If you set a job's priority through sorted[0], code reading the same job through jobs sees the edit.

To change a priority, build a new job object at that index and pass it to with(). Keep the other entries by reference when you only need to change one.