DEV Community

Manthan Ankolekar
Manthan Ankolekar

Posted on • Edited on

New Array methods in JavaScript

with() method - It is used to assign an existing array to a new array

var arr = [1, 6, 3, 4, 5];

var newArr = arr.with(1, 2);

console.log(newArr); // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

toSorted() method - It is used to sort the elements of an array.

var arr = [1, 5, 3, 2, 4];

var sortedArr = arr.toSorted();

console.log(sortedArr); // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

toReversed() method - It is used to reverse the order of the elements of an array.

var arr = [1, 5, 3, 2, 4];

var reversedArr = arr.toReversed();

console.log(reversedArr); // [4, 3, 2, 5, 1]
Enter fullscreen mode Exit fullscreen mode

toSpliced() method - It is used to remove and/or add elements to an array.

var arr = [1, 5, 3, 2, 4];

var newArr = arr.toSpliced(0, 2);

console.log(newArr); // [3, 2, 4]
Enter fullscreen mode Exit fullscreen mode

Top comments (6)

Collapse
 
milandev profile image
Milanin • Edited

I think you should also mention that toSpliced toReversed and toSorted are immutable methods. I find it really awesome, that we finally got immutable versions of sort reverse and splice methods in JavaScript!

Collapse
 
manthanank profile image
Manthan Ankolekar

Yes

Collapse
 
saadh393 profile image
Saad Hasan

Image description

You have write it wrong here, it should be - [4, 2, 3, 5, 1]
Maybe by mistake you have sorted the elements

Collapse
 
manthanank profile image
Manthan Ankolekar

I have changed it.✌️

Collapse
 
manthanank profile image
Manthan Ankolekar

Oh, yes. Thanks for informing.

Collapse
 
panayiotisgeorgiou profile image
Panayiotis Georgiou

Thanks for sharing!