Functions for 2023
Immutability
- Array.prototype.toSpliced()
- Array.prototype.toSorted()
- Array.prototype.toReversed()
- Array.prototype.with()
The above methods look like existing methods we've had for decades but with one key difference: they return new copies of arrays. This has various implications, especially if you're using a framework like React.
Previously, to avoid mutating an original, you'd first make a copy the array by using from()
, slice()
, or the spread operator. Now you can do it on the fly.
with()
is a cool new trick that allows you to alter an item in an array at specific index while returning the entire array without mutating the original.
const fruits = ['🍐', '🍑', '🍒', '🍍', '🍇', '🍌']; console.log( fruits.with(2, '🍉') ); // ['🍐', '🍑', '🍉', '🍍', '🍇', '🍌']
Coming Soon: Object.groupBy()
The Object.groupBy() static method groups the elements of a given iterable according to the string values returned by a provided callback function. The returned object has separate properties for each group, containing arrays with the elements in the group.
Object.groupBy() - Javascript | MDN
Whatever you say, MDN technical writers! Basically, you can group an array without using a library like Lodash and without writing a complex reduce()
function.
const sports = [ { name: 'Rugby Union', contact: 'full' }, { name: 'Tennis', contact: 'noncontact' }, { name: 'American Football', contact: 'full' }, { name: 'Wrestling', contact: 'full' }, { name: 'AFL', contact: 'semi' }, { name: 'Sailing', contact: 'noncontact' }, ]; // using a reduce() function console.log( sports.reduce((groups, sport) => { if (groups[sport.contact] !== undefined) { groups[sport.contact].push(sport); } else { groups[sport.contact] = [sport]; } return groups; }, {}) ); // using the new Object.groupBy() method console.log( Object.groupBy(sports, (sport) => sport.contact) ); // both functions return... const output = { "full": [ { "name": "Rugby Union", "contact": "full" }, { "name": "American Football", "contact": "full" }, { "name": "Wrestling", "contact": "full" } ], "noncontact": [ { "name": "Tennis", "contact": "noncontact" }, { "name": "Sailing", "contact": "noncontact" } ], "semi": [ { "name": "AFL", "contact": "semi" } ] }