A lot of everyday JavaScript is still written the 2015 way: arr[arr.length - 1], [...arr].reverse().find(), a 5-line reduce just to group items. Over the last few years, JavaScript added built-in methods for all of these. They work in every modern browser and in Node.js 21+ (Object.groupBy is the newest of them).
I ran every snippet below on Node.js 22. The comments show the real output.
Prefer video? Here's the short version:
1. .at(): get the last item without the length math
const scores = [42, 87, 15, 99, 63];
// before
const last = scores[scores.length - 1];
// after
scores.at(-1); // 63
scores.at(-2); // 99
scores.at(0); // 42
Negative indexes count from the end. It also works on strings, and an out-of-range index returns undefined instead of throwing:
"hello".at(-1); // "o"
scores.at(10); // undefined
2. .findLast(): search from the end
Want the most recent paid order? The old trick copies and reverses the whole array:
const lastPaid = [...orders].reverse().find(o => o.status === "paid");
findLast searches from the end directly, without the copy:
const orders = [
{ id: 1, status: "paid" },
{ id: 2, status: "pending" },
{ id: 3, status: "paid" },
{ id: 4, status: "refunded" },
];
orders.findLast(o => o.status === "paid"); // { id: 3, status: 'paid' }
orders.findLastIndex(o => o.status === "paid"); // 2
3. .toSorted(): sort without mutating (and without the string trap)
sort() has two surprises. It changes the original array, and without a compare function it sorts numbers as strings:
const nums = [10, 1, 5];
const sorted = nums.sort();
sorted; // [1, 10, 5] 😬
nums; // [1, 10, 5] (the original changed too)
sorted === nums; // true: it's the same array
That's a classic source of bugs in React state and anywhere else you share arrays. toSorted() returns a new array and leaves the original alone:
const nums = [10, 1, 5];
const sorted = nums.toSorted((a, b) => a - b);
sorted; // [1, 5, 10]
nums; // [10, 1, 5] untouched
Note that toSorted() doesn't fix the string comparison. Called without a compare function, it still returns [1, 10, 5]. Always pass (a, b) => a - b for numbers.
4. .toReversed() and .with(): immutable updates
Same idea for reversing and for replacing one item:
const letters = ["a", "b", "c"];
letters.toReversed(); // ["c", "b", "a"]
letters.with(1, "B"); // ["a", "B", "c"]
letters; // ["a", "b", "c"] unchanged
with() is perfect for state updates (setItems(items.with(i, newItem))). Unlike arr[i] = x, it refuses to create holes. An out-of-range index throws:
letters.with(5, "x"); // RangeError: Invalid index : 5
There's also toSpliced(), the non-mutating version of splice().
5. Object.groupBy(): grouping without reduce
The reduce version works, but nobody enjoys reading it:
const byRole = people.reduce((acc, p) => {
(acc[p.role] ??= []).push(p);
return acc;
}, {});
Now it's one line:
const people = [
{ name: "Ana", role: "dev" },
{ name: "Bo", role: "design" },
{ name: "Cy", role: "dev" },
];
const byRole = Object.groupBy(people, p => p.role);
// { dev: [Ana, Cy], design: [Bo] }
Two details: it's Object.groupBy(array, fn), not array.groupBy(fn), and the result has a null prototype, so it has no hasOwnProperty or other inherited methods. If your keys aren't strings (objects, dates…), use Map.groupBy() instead, which returns a Map.
Cheat sheet
| Old way | Modern way |
|---|---|
arr[arr.length - 1] |
arr.at(-1) |
[...arr].reverse().find(fn) |
arr.findLast(fn) |
[...arr].sort(fn) |
arr.toSorted(fn) |
[...arr].reverse() |
arr.toReversed() |
copy = [...arr]; copy[i] = x |
arr.with(i, x) |
reduce into groups |
Object.groupBy(arr, fn) |
Which of these are you going to use first? Tell me in the comments.
I post one tested coding tip every day on YouTube at Refactorly. The 30-second version of this one is here.
Top comments (0)