New addition to JS array methods

Hero image for New addition to JS array methods

Newest methods

‼️ Not supported in Firefox until version 114

These new methods returns the copy of the original array

with(index, value) Returns a new array with the element at index replaced with value.

const numbers = [1, 2, 3]
console.log(numbers.with(1, 4)) // [1, 4, 3]
console.log(numbers) // [1, 2, 3]

toSorted() Returns a new array with the elements sorted in ascending order.

const cities = ['New York', 'Warsaw','Miami', 'Florida']
console.log(cities.toSorted()) // ['Florida', 'Miami', 'New York', 'Warsaw']
console.log(cities) // ['New York', 'Warsaw','Miami', 'Florida']

toReversed() Returns a new array containing the elements in reversed order.

const cities = ['New York', 'Warsaw','Miami', 'Florida']
console.log(cities.toReversed()) // ['Florida', 'Miami', 'Warsaw', 'New York']
console.log(cities) // ['New York', 'Warsaw','Miami', 'Florida']

toSplice(startIndex, deleteCount, string[]) Returns a new array that consists of all elements before start, item1, item2, …, itemN, and all elements after start + deleteCount.

const cities = ['New York', 'Warsaw','Miami', 'Florida']
console.log(cities.toSpliced(0, 2, 'Torun')) // ['Torun', 'Miami', 'Florida']
console.log(cities) // ['New York', 'Warsaw','Miami', 'Florida']