Solve - sort is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Andrew Neel

Solve - sort is not a function Error #

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 you're calling the sort() method on 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 and got the error back.

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 a 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 on it, otherwise we return an empty array. This way, you 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 and make sure you have parsed it to a native JavaScript array before calling the sort method on it.

If you have an array-like object which you're trying to convert to an array before calling the sort method, use the Array.from method.

index.js
const set = new Set(['c', 'b', 'a']); const result = Array.from(set).sort(); console.log(result); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c']

Before calling the sort method, we convert the value to an array.

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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee