Join the social network of Tech Nerds, increase skill rank, get work, manage projects...

• # How to do Array Sort

• 0
• 0
• 0
• 0
• 0
• 0
• 0
• 0
• 47
Comment on it

Use the Array objects sort method:

```var fruitArray = ['strawberry','apple','orange','banana','lime'];

The Array objects sort method sorts the array elements alphabetically. To make the sort easy, all data types are converted to their string equal in value before sorting:

```var numberArray = [4,13,2,31,5];
```

In this example the numbers are the array members, theyre sorted in lexicographical (dictionary) order, not numerically. To do an actual numeric sort, use a custom sort function:

```function compareNumbers(a,b) {
return a - b;
}
var numArray = [13,2,31,4,5];
```

The second parameter value will be subtracted by the function from the first, Also if the second value is greater then the first one then the positive value will be returned else the it will return negative. If the return value is less than zero, the sort index for the second parameter is set higher than the first parameter. If the value is greater than zero, the sort index for the first parameter is set higher than the other. If the value is exactly zero, the sort index for the two is unchanged.
If the array elements contain strings that could be converted to numbers, then the compare Numbers sort function still works, as number conversion is automatic:

```var numberArray=["34","4","5"];
```

The sort method sorts the elements in an ascending order. If you want to do a reverse sort, use the sort method to sort the elements, and then use the reverse method to reverse the array member order:

```var numberArray = [4,5,1,3,2];
numberArray.sort();
numberArray.reverse(); // array now has 5,4,3,2,1
```

## 0 Comment(s)

OR
OR
Register

OR
Fill out the form below and instructions to reset your password will be emailed to you:

• Hire
• Post Projects

### Post Projects

• All at 0 Cost ....
• Post Tech Job
• Select Best Bidder
• Track the Project
• Approve Work and Pay safely
• Browse Nerds
• Work
• Find Projects Find Projects
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
View more...
View less...
• Manage
• Company Company

### Manage Company

• All at 0 Cost ....
• Manage Company and Employee Profiles
• Company wide Employee Productivity Reports
• Knowledge Sharing and Collaboration Tools
• Get Sales Lead and Bid for Tech Projects
• Send Invoices and Receive Payment Safely
• Learn
• Nerd Digest Nerd Digest
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
View more...
View less...
• Tech Q & A Tech Q & A
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
View more...
View less...