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.