brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: toSorted() sorts an array without changing the original

Javascript
~/tips/tip-javascript-tosorted

const sorted = names.toSorted();

Returns a new sorted array and leaves the array you started with as it was.

sort() changes the array in place, which bites you when something else still uses it.

const names = ["Eva", "Bram", "Anouk"];
const sorted = names.toSorted();
// sorted: ["Anouk", "Bram", "Eva"]
// names:  ["Eva", "Bram", "Anouk"]

There are matching toReversed() and toSpliced(). They are in current browsers and in Node 20 and later, so check your target before you use them. Like sort(), the default sorts as text, so numbers need a compare function.

Further reading: Array.prototype.toSorted on MDN

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link