Skip to content

Sort, reverse and update arrays without mutating: toSorted, toReversed, with

JavaScript Dasun Kalupahana 86 views

const nums = [3, 1, 2];
const sorted = nums.toSorted((a, b) => a - b);
const reversed = nums.toReversed();
const replaced = nums.with(0, 99);
console.log(nums, sorted, reversed, replaced);
console.log(nums.findLast(n => n > 1));
// [ 3, 1, 2 ] [ 1, 2, 3 ] [ 2, 1, 3 ] [ 99, 1, 2 ]
// 2

These methods return a new array and leave the original untouched, which suits React state and other immutable code. Needs Node 20+, Chrome 110, Firefox 115 or Safari 16.

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.