ES2023 Features

.toSorted

				
					/*1..toSorted */

//traditional sort
//it mutates
var arr = [1,54,2,14,6]
var newArr= arr.sort((a,b)=>a-b);
console.log(arr); //[ 1, 2, 6, 14, 54 ]
console.log(newArr); //[ 1, 2, 6, 14, 54 ]
/*original array also gets sorted..
but what if we dont want to disturb 
the original array then use .toSorted()*/

var arr1 = [1,54,2,14,6]
var newArr1= arr.toSorted((a,b)=>a-b);
console.log(arr1); //[ 1, 54, 2, 14, 6 ]
console.log(newArr1); //[ 1, 2, 6, 14, 54 ]
				
			

2.FindLast()

				
					/*finds the last element in the array.. 
it doesnt sort anything..*/

const arr2 = [27, 28, 30, 66, 42, 35, 300];
let last1 = arr2.findLast(x => x);
let last2 = arr2.findLast(x => x > 20);
let last3 = arr2.findLast(x => x > 20 && x < 300);
console.log(last1);//300
console.log(last2);//300
console.log(last3);//35
				
			

3.toReversed()

				
					const arr3 = [27, 28, 30, 40, 42, 35, 300];
let reverse = arr2.toReversed();
console.log(reverse);//[300,35,42,66,30,28,27]
				
			

4.with(index,value)

				
					const arr4 = [1,23,222,63,88]
console.log(arr4.with(2,555));//[ 1, 23, 555, 63, 88 ]
console.log(arr4.with(1,555));//[ 1, 555, 222, 63, 88 ]
console.log(arr4);//[1,23,222,63,88]
var newArr4 = arr4.with(1,1000);
console.log(newArr4);//[ 1, 1000, 222, 63, 88 ]
				
			

Leave a Comment