Question

Javascript Sort method

I found this very informative post on the subject of the Javascript SORT method. I found, however, that VS Code does not recognize the method.

This is the error message I got:

numbers.sort((a,b) => a - b); ^

TypeError: numbers.sort is not a function

Has anyone else run into this?


Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Andy Hattemer
DigitalOcean Employee
DigitalOcean Employee badge
October 23, 2020
Accepted Answer

That error looks like the type that you get when your numbers variable is not actually typed as an Array.

For example, if you have some code where the numbers variable was an object or an integer or a string:

var numbers ="1,6,3";
numbers.sort((a,b) => a - b);

You will get Uncaught TypeError: numbers.sort is not a function because there is no sort function for strings.

But if you check this exact snippet of code:

var numbers = [3,6,1];
numbers.sort((a,b) => a - b);

You should definitely not see any errors.

When you say:

VS Code does not recognize the method

This makes me think you are seeing IDE debugging warnings which could also be due to other problems with the your VS Code and extensions config.

But my first recommendation on debugging would be to check the TYPE of the numbers variable just before you call numbers.sort() and confirm that it is an Array

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.