This content originally appeared on DEV Community and was authored by Christian Heilmann
JavaScript now has a way to change elements, sort, reverse and splice arrays without changing the original, thus giving it immutability. The new methods are with(), toSorted(), toReversed() and toSpliced(). No need to create a copy with [...arr] first. Only missing support is Firefox.
const arr = ['f','c','k','a','f','d'];
const newArr = arr.with(2,'m');
// newArr -> ['f', 'c', 'm', 'a', 'f', 'd']
const sortArr = arr.toSorted();
// sortArr -> ['a', 'c', 'd', 'f', 'f', 'k']
const reverseArr = arr.toReversed();
// reverseArr -> ['d', 'f', 'a', 'k', 'c', 'f']
const splicedArr = arr.toSpliced(3, 3, 'it');
// splicedArr -> ['f', 'c', 'k', 'it']
This content originally appeared on DEV Community and was authored by Christian Heilmann
Christian Heilmann | Sciencx (2023-06-06T14:53:21+00:00) New array methods in JavaScript bring immutability. Retrieved from https://www.scien.cx/2023/06/06/new-array-methods-in-javascript-bring-immutability-2/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.