One property of the Array.prototype.sort() function is that it is an inplace sorting algorithm, which means it does not create a new copy of the array to be sorted, it sorts the array without using any extra space, making it more efficient and performant. But this characteristic sometimes leads to an awkward situation.
Let’s understand this with an example. Assume, we have a names array with some string literals We want to keep the order of this array intact and want another array containing the same elements as the names array but sorted alphabetically.
We can do something like this −
const names = ['Rakesh', 'Mukesh', 'Ram', 'Anshul', 'Dheeraj']; let sortedNames = names; sortedNames = sortedNames.sort(); console.log(names); console.log(sortedNames);
1. Using slice() while initializing new array
const names = ['Rakesh', 'Mukesh', 'Ram', 'Anshul', 'Dheeraj']; let sortedNames = names.slice(); sortedNames = sortedNames.sort(); console.log(names); console.log(sortedNames);
The slice() method actually returns a shallow copy, copied into a new array of the array it is used with, if no arguments are provided it copies from start to end.
While this method is not very efficient as it includes initialising a new array and only effective with array of String / Number literals, the second method is bit more efficient and works well with array of objects as well.
2. Using JSON.stringify() / JSON.parse()
const names = ['Rakesh', 'Mukesh', 'Ram', 'Anshul', 'Dheeraj']; let sortedNames = JSON.parse(JSON.stringify(names)); sortedNames = sortedNames.sort(); console.log(names); console.log(sortedNames);
Converting the array into a JSON string and back into an array in a way forces the compiler to not copy by reference.
Output for both of the methods will be same in the console −
[ 'Rakesh', 'Mukesh', 'Ram', 'Anshul', 'Dheeraj' ] [ 'Anshul', 'Dheeraj', 'Mukesh', 'Rakesh', 'Ram' ]
- Related Articles
- Sort arrays of objects in Java
- Sort only numbers from alphanumeric string in MySQL?