AppDividend
Latest Code Tutorials

Sorting Arrays in Javascript | Array sort() Tutorial Example

319

Get real time updates directly on you device, subscribe now.

Sorting Arrays in Javascript | Array sort() Tutorial Example is today’s leading topic. The sort() method available on the Array prototype allows you to sort the elements of an array. It accepts an optional callback function that you could use to tailor the sorting mechanism to your specific needs. Sorting strings can get quite opinionated because of how the sort method works. We use Node.js as a demonstration of examples for this tutorial.

Sorting Arrays in Javascript | Array sort()

If you have not installed the Node.js in your machine, then please install it. Otherwise, you can perform the operations in a browser as well but for that, you need to create an HTML page and include the javascript, and then you can start with this tutorial.

If you want to use Node.js then also it is okay because ultimately we need to perform the operations in Javascript. So the choice is yours. I am using Node.js.

Create one folder called node-examples and go inside that folder.

mkdir node-examples
cd node-examples

Open the project folder inside VSCode or any other editor.

code .

Create one file inside that folder called server.js.

You can also install nodemon if you do not want to restart the node server manually every time. But, first, initialize the package.json file.

npm init -y

Now install the nodemon package.

npm install nodemon --save-dev

Finally, start the Node.js server using the following command.

nodemon server

#Sorting an Array

The sort() method sorts an array alphabetically:

Write the following code inside the server.js file.

let musicians = ["Drake", "JB", "MJ", "CP"];
console.log(musicians.sort());

 

Sorting Arrays in Javascript | Array sort()

#Numeric Sort

By default, the sort() function sorts values as stringsThis works well for strings (“CP” comes before “Drake”). However, if the numbers are sorted as strings, “35” is bigger than “100”, because “3” is bigger than “1”. Because of this, the sort() method will produce an incorrect result when sorting numbers. We can fix this by creating a compare function.

If you want to sort the array in Descending order, then you can write the following code.

// server.js

let points = [30, 100, 2, 8, 65, 10];
let sortedDescPoints = points.sort((a, b) => {
  return b - a;
});
console.log(sortedDescPoints);

 

Numeric Sort

The compare function will return a negative, zero, or positive value, depending on the arguments.

If you want to sort in Ascending order, then please write the following code.

// server.js

let points = [30, 100, 2, 8, 65, 10];
let sortedDescPoints = points.sort((a, b) => {
  return a - b;
});
console.log(sortedDescPoints);

#Sorting an Array in Random Order

Write the following code to get the order randomly.

// server.js

let points = [30, 100, 2, 8, 65, 10];
let sortedDescPoints = points.sort((a, b) => {
  return 0.5 - Math.random();
});
console.log(sortedDescPoints);

#Sorting Object Arrays

JavaScript arrays often contain objects. Even if objects have properties of different data types, the sort() method can be used to sort the array. Write the following code.

// server.js

let stocks = [
  { type:"Apple", year:1975 },
  { type:"Microsoft", year:1976 },
  { type:"Amazon", year:1995 }
];

let sortedDescStocks = stocks.sort((a, b) => {
  return b.type - a.type;
});
console.log(sortedDescStocks);

 

Related Posts
1 of 13

Sorting Object Arrays

Finally, our Sorting Arrays in Javascript | Array sort() tutorial example is over. Thanks for taking.

1 Comment
  1. Tim says

    Krunal, should the final list be sorted? Your example (and when I ran it myself) does not sort the array, it is identical in order.

    Tim

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.