Unlocking the Power of Arrays: Exploring Array.with(), Array.toSorted(), Array.toReversed(), and Array.toSpliced() Methods

A comprehensive guide to harnessing the versatility and efficiency of array manipulation in modern programming

In Javascript as arrays work as reference type, and if we want to perform insertion , deletion , sorting and reversal without modifying original array, then we have to first create a copy of original array, so that we don’t modify the original one.

Here is an example:

const arr = ["Radha","Krishna"];

// insertion
const newArr = [...arr];
newArr[1] = "Virndavan";

// sorting
const sorted = [...arr].sort(); // doing one extra step, [...arr]

// reversal
const reversed = [...arr].reverse); // doing one extra step, [...arr]

// deletion
const filtered = [...arr].splice(0,1); // doing one extra step, [...arr]

Recently (in Feb) 4 new Array methods have been introduced which will remove the copying step.
These methods are:

Array.with(index, value);

const arr = ["Radha", "Krishna"];

// Old Way
const newArr = [...arr];
newArr[1] = "Vrindavan";

// New Way

const newArr = arr.with(1, "Vrindavan"); // No Copying Required, with() method
// will not modify the original array.

Array.toSorted()

const arr = ["Radha", "Krishna"];

// Old Way
const newArr = [...arr].sort();

// New Way

const newArr = arr.toSorted(); // No Copy Needed

Array.toReversed()

const arr = ["Radha", "Krishna"];

// Old Way
const newArr = [...arr].reverse();

// New Way

const newArr = arr.toReversed(); // No Copy Needed

Array.toSpliced()

const arr = ["Radha", "Krishna"];

// Old Way
const newArr = [...arr].splice(0,2);

// New Way
const arr = ["Radha", "Krishna"];
const newArr = arr.toSpliced(0,1); // No Copy Needed

Caveat: As these methods are new, they support majority of browsers but right now they aren’t supported by Firefox and Opera, but in few months they will be supported everywhere.

EDIT 17 Aug 23: Supported in all major browsers.

Check Support Here and Here

--

--

राहुल मिश्रा
राहुल मिश्रा

Responses (2)