ECMAScript 2023, the 14th edition, introduced the toSorted, toReversed, with, findLast, and findLastIndex
-
ECMAScript 2023, the 14th edition, introduced the
toSorted
,toReversed
,with
,findLast
, andfindLastIndex
toSorted
: The toSorted() method of Array instances is the copying version of the sort() method. It returns a new array with the elements sorted in ascending order.const months = ["Mar", "Jan", "Feb", "Dec"]; const sortedMonths = months.toSorted(); console.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar'] console.log(months); // ['Mar', 'Jan', 'Feb', 'Dec'] const values = [1, 10, 21, 2]; const sortedValues = values.toSorted((a, b) => a - b); console.log(sortedValues); // [1, 2, 10, 21] console.log(values); // [1, 10, 21, 2]
toReversed
: The toReversed() method of Array instances is the copying counterpart of the reverse() method. It returns a new array with the elements in reversed order.const items = [1, 2, 3]; console.log(items); // [1, 2, 3] const reversedItems = items.toReversed(); console.log(reversedItems); // [3, 2, 1] console.log(items); // [1, 2, 3]
with
: The with() method of Array instances is the copying version of using the bracket notation to change the value of a given index. It returns a new array with the element at the given index replaced with the given value.const arr = [1, 2, 3, 4, 5]; console.log(arr.with(2, 6)); // [1, 2, 6, 4, 5] console.log(arr); // [1, 2, 3, 4, 5]
findLast
: The findLast() method iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, undefined is returned.const array1 = [5, 12, 50, 130, 44]; const found = array1.findLast((element) => element > 45); console.log(found); // Expected output: 130
findLastIndex
: The findLastIndex() method iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.const array1 = [5, 12, 50, 130, 44]; const isLargeNumber = (element) => element > 45; console.log(array1.findLastIndex(isLargeNumber)); // Expected output: 3 // Index of element with value: 130
-