Skip to content

New Immutable Array Methods available in JavaScript

Published: at 12:02 PM

I just learned that several new immutable array methods are available in the latest versions of all the major browsers. I have a utility file that has several homemade versions of these functions in it, so it’ll be nice to pare that down a bit. I’m going to go over the new methods and show how they can be used.

Array.prototype.toReversed()

Array.prototype.toReversed() is similar to Array.prototype.reverse(), but it returns a new array instead of mutating the original array.

const names = ["Ras", "Candace", "Eli", "Ezra"];

const reversedNames = names.toReversed();

console.log(names); // ['Ras', 'Candace', 'Eli', 'Ezra']
console.log(reversedNames); // ['Ezra', 'Eli', 'Candace', 'Ras']

Array.prototype.toSorted()

Array.prototype.toSorted() is similar to Array.prototype.sort(), but it returns a new array instead of mutating the original array. It also has a second parameter that allows you to pass in a custom sort function.

const names = ["Ras", "Candace", "Jim", "Claude"];

const sortedNames = names.toSorted();

console.log(names); // ['Ras', 'Candace', 'Jim', 'Claude']
console.log(sortedNames); // ['Candace', 'Claude', 'Jim', 'Ras']

const sortedByLength = names.toSorted((a, b) => a.length - b.length);

console.log(sortedByLength); // ['Jim', 'Ras', 'Claude', 'Candace']

Array.prototype.toSpliced()

Array.prototype.toSpliced() is the immutable version of Array.prototype.splice() method, but it returns a new array instead of mutating the original array. It has optional parameters that allow you to pass in items to be inserted into the array and the number of items to be removed from the array. More info on Array.prototype.toSpliced() can be found here.

const names = ["Ras", "Candace", "Jim", "Claude"];
const spliced = names.toSpliced(1, 0, "William");

console.log(names); // ['Ras', 'Candace', 'Jim', 'Claude']
console.log(spliced); // ['Ras', 'William', 'Candace', 'Jim', 'Claude']

const spliced2 = names.toSpliced(1, 1, "Stanley");

console.log(names); // ['Ras', 'Candace', 'Jim', 'Claude']
console.log(spliced2); // ['Ras', 'Stanley', 'Jim', 'Claude']

const spliced3 = names.toSpliced(1, 2, "Stanley", "John");

console.log(names); // ['Ras', 'Candace', 'Jim', 'Claude']
console.log(spliced3); // ['Ras', 'Stanley', 'John', 'Claude']

This final one is not available in all browsers at the time of this writing.

Array.prototype.with()

The Array.prototype.with() method is the immutable equivalent to using bracket notation to change an element at a given index. It returns a new array instead of mutating the original array.

const names = ["Ras", "Candace", "Jim", "Claude"];
const withNames = names.with(1, "Stanley");

console.log(names); // ['Ras', 'Candace', 'Jim', 'Claude']
console.log(withNames); // ['Ras', 'Stanley', 'Jim', 'Claude']