TypeError: sort is not a function in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 29, 2022

banner

Photo from Unsplash

TypeError: sort is not a function in JavaScript #

The "sort is not a function" error occurs when we call the sort() method on a value that is not an array. To solve the error, convert the value to an array, or make sure to only call the sort method on valid arrays.

typeerror sort is not a function

Here is an example of how the error occurs.

index.js
const arr = {}; // ⛔️ Uncaught TypeError: arr.sort is not a function const result = arr.sort();

We called the Array.sort() method on an object, which caused the error.

To solve the error, console.log the value you're calling the sort method on and make sure it's a valid array.

index.js
const arr = ['d', 'c', 'a', 'b']; // 👇️ ['a', 'b', 'c', 'd'] console.log(arr.sort());

You can conditionally check if the value is an array by using the Array.isArray method.

index.js
const arr = null; const result = Array.isArray(arr) ? arr.sort() : []; console.log(result); // 👉️ []

We used the ternary operator, which is very similar to an if/else statement.

If the value is an array, we return the result of calling the sort method, otherwise we return an empty array.

This way, we won't get an error, even if the value is not an array.

If the value is fetched from a remote server, make sure it is of the type you expect it to be by logging it to the console. Also, ensure you have parsed the value to a native JavaScript array before calling the sort method.

If you have an array-like object, use the Array.from method to convert it to an array.

index.js
const set = new Set(['c', 'b', 'a']); const result = Array.from(set).sort(); console.log(result); // 👉️ ['a', 'b', 'c']

We used the Array.from method to convert the Set object to an array before calling sort().

You could also use the spread syntax to achieve the same result.

index.js
const set = new Set(['c', 'b', 'a']); const result = [...set].sort(); console.log(result); // 👉️ ['a', 'b', 'c']

Either way, the array-like object is converted to an array, on which we can call the sort() method.

Conclusion #

The "sort is not a function" error occurs when we call the sort() method on a value that is not an array. To solve the error, convert the value to an array, or make sure to only call the sort method on valid arrays.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.