How to Fix TypeError: set.sort is not a function in JavaScript

To fix the TypeError: set.sort is not a function error, convert the input value to an array or ensure to call the .sort() method on valid arrays.

TypeError: set.sort is not a function error occurs in JavaScript when you call the “.sort()” method on a value that is not an array.

The main reason for the set.sort is not a function error because we call the .sort() method on Set, which is not a type of Array.

Reproduce the error

const set = new Set([46, 21, 19]);

console.log(set.sort());

Output

TypeError: set.sort is not a function

How to fix it?

You can fix the TypeError: set.sort is not a function error by using the Array.from() method to convert the set to an array before calling sort().

const set = new Set([46, 21, 19]);

console.log(Array.from(set).sort());

Output

[ 19, 21, 46 ]

And we successfully fixed the TypeError.

Ensure the Object is an Array

Before calling .sort(), ensure that the object you’re working with is an array.

const set = new Set([46, 21, 19]);

if (Array.isArray(set)) {
  set.sort();
}

console.log("Convert the value to an array")

Output

Convert the value to an array

By using Array.isArray() method, you can ensure that you are only calling the sort() method on actual arrays, preventing the “TypeError: sort is not a function” error.

That’s it!

Related posts

TypeError: Observable.of is not a function

TypeError: Cannot read property ‘value’ of null

TypeError: this.getOptions is not a function