DEV Community

Cover image for Guide to : toReversed, toSorted and toSpliced
Abhijeet kumar
Abhijeet kumar

Posted on

Guide to : toReversed, toSorted and toSpliced

In JavaScript, there are numerous built-in functions available, some of which are commonly used in everyday problem-solving scenarios, while others are less frequently utilized. Let’s explore some of these less commonly used built-in functions.

We will thoroughly explore every aspect of those lesser-utilized built-in functions .

Let’s exploration.

  1. toReversed — this is similar to the reverse in JavaScript but different in between in that reverse perform of change the original array while toReversed make his own instance of array and transpose element and don’t effect of original array.

Example —

// toReversed  's example 

let arr = [ '🤖', '👽','🤷‍♂️' 'whatever...']

console.log(arr.toRevered()) // it don't take any argument 

// Output - [ 'whatever...' ,'🤷‍♂️' , '👽' , '🤖']

console.log(arr)

// original array - [ '🤖', '👽','🤷‍♂️' 'whatever...']
Enter fullscreen mode Exit fullscreen mode

Use case with sparsely array : toReversed element should be sparse if that will at those time its return undefined .

Example —

// toReversed 's example with sparsely array 

let array = [ '🤖', '👽','🤷‍♂️' 'whatever...' , , ]
console.log(array.toRevered()) // it don't take any argument 
// Output - [ undefined , 'whatever...' ,'🤷‍♂️' , '👽' , '🤖']
Enter fullscreen mode Exit fullscreen mode

If you attempt to perform the transpose with toReversed operation on a non-array object, it iterates through each property of the object. For properties with integer keys, it reverses their values, while for non-integer keys, it returns undefined. This behaviour ensures consistency even when operating on non-array objects.

Example —

const arrayLike = {
  color: 'Carbon black',
  brand: 'Dassault Falcon 7X',
  2: 4,
  4:4,
};
console.log(Array.prototype.toReversed.call(arrayLike));
// [4, 4, undefined, undefined]
// here 0 , 1 index become undefined 
Enter fullscreen mode Exit fullscreen mode

2. toSorted —The toSorted function works just like sort, but it's more careful. While sort messes with your original array, toSorted takes a copy of it, sorts the copy, and leaves your original array untouched. It's like having a tidy clone do the sorting while your original stays safe and sound.

by default it is return a ascending sorted new array copy of given array but by providing compare argument we can change it as well.

It is take argument as the compare function. which is optional by default it sort the array element in ascending order.

Example —

let arr = [ 'India' , 'USA' , 'Germany' ,'Russia']

let sorted = arr.toSorted() 

// Output - ['Germany', 'India', 'Russia', 'USA']

console.log(arr)

// Original array - [ 'India' , 'USA' , 'Germany' ,'Russia']
Enter fullscreen mode Exit fullscreen mode

Use case with sparsely array : As we already discussed that if there ‘ll be any spares array element at that will become as undefined .

let see with example —

// toSroted with sparse array 

console.log([, undefined, "a", "b" ,"c" ].toSorted()); 

// Output -  ["a", "b","c" , undefined, undefined]
Enter fullscreen mode Exit fullscreen mode

When using toSorted with non-array objects, it behaves similarly to the function discussed earlier. In this case, keys that are integers will be sorted, while their corresponding values will also be sorted accordingly. However, non-integer keys will be treated as undefined.

const arrayLike = {
  length: 3,
  color: "mettalic black",
  0: 5,
  2: 4,
};

console.log(Array.prototype.toSorted.call(arrayLike));
// Output - [4, 5, undefined]
Enter fullscreen mode Exit fullscreen mode
  1. **toSpliced — **we ‘re already familiar with splice ( inserting , replace , deletion ) in build function just like with toSpliced function we can also insert , replace and delete the elements from array but it don't modified the original array.

And here we also about cover all operation which we can perform with toSpliced function.

Syntax :

toSpliced(start, deleteCount, item1, item2, item3 , ....itemN)
Enter fullscreen mode Exit fullscreen mode

Let’s break it down further to understand its intricacies.

start-

The index at which changes in the array will begin is specified as a zero-based integer.

  • If a negative index is provided, it counts backward from the end of the array.

  • If the starting index is less than the negative length of the array or if it’s omitted, the operation will start from the beginning (index 0).

  • If the starting index is equal to or greater than the length of the array, no elements will be deleted. Instead, elements will be added based on the provided values.

deleteCount (optional parameter )-

This parameter indicates the number of elements to remove from the array, starting from the specified index.

  • If deleteCount is not provided or is greater than or equal to the number of elements after the specified start index, all elements from the start index to the end of the array will be removed.

  • If you want to remove all elements after the start index and also pass additional items, you must use Infinity as the deleteCount.

  • If deleteCount is 0 or negative, no elements are removed. In such cases, you should add at least one new element.

item1 …itemN **(optional parameter )-**

These are the elements that will be added to the array, starting from the specified index.

in case we don’t specify any elements, toSpliced() will only remove elements from the array.

Example —

// insertion , deletion and replace using toSpliced

const countries = ["India", "USA", "UK", "Russia"];

// insertion an element at index 1

const newCountries = countries.toSpliced(1, 0, "China");

console.log(newCountries); // ["India","China", "USA", "UK", "Russia"]

// deletion of two elements starting from index 2

const countryDeleted = newCountries.toSpliced(2, 2);
console.log(countryDeleted); // ["India","China", "USA"]

// replace a element at index 1 with three new array element
const countryNameReplaced = countryDeleted.toSpliced(1, 1, "Japana", "South Korea");

console.log(countryNameReplaced); // ["India","Japana" , "South Korea", "USA"]

// there 're no changes in original array 

console.log(countries); // ["India", "USA", "UK", "Russia"]
Enter fullscreen mode Exit fullscreen mode

In toSpliced , sparsely and non array object behaviour are similar as we have discussed respectively in toReversed() and toSorted().

Conclusion — Each of these functions serves a specific role in helping developers to effectively arrange and change arrays in JavaScript. By grasping how to use them, we can improve their code’s capabilities and speed.

Happy coding !!

Top comments (0)