Fix Problem with .sort() method in JavaScript, two arrays sort instead of only one


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);

But as we know in JavaScript, arrays are also objects and objects are copied by reference and not by value, so sorting one array results in sorting of both arrays, which we obviously don’t want.

Solutions

1. Using slice() while initializing new array

Example

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()

Example

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 −

Output

[ 'Rakesh', 'Mukesh', 'Ram', 'Anshul', 'Dheeraj' ]
[ 'Anshul', 'Dheeraj', 'Mukesh', 'Rakesh', 'Ram' ]

Updated on: 18-Aug-2020

168 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements