Sorting Arrays In JavaScript

Sorting Arrays In JavaScript: Hello everyone, welcome to the website. In this article we will going to discuss about the Sorting Arrays In JavaScript.

Sorting Arrays In JavaScript

JavaScript provides several methods to sort arrays, including the sort() method, which is the simplest way to sort an array. By default, it sorts the elements in ascending order according to their Unicode code points. For example:

Code 1 For .sort() Method In JavaScript

let fruits = ['banana', 'apple', 'kiwi', 'mango'];


[‘apple’, ‘banana’, ‘kiwi’, ‘mango’]

If you want to sort the elements in a specific order, you can pass a comparison function as an argument to the sort() method. The comparison function should return a negative, zero, or positive value, depending on the arguments, like:

Code 2 For .sort() Method In JavaScript

let numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;


[1, 2, 3, 4, 5]

Another way to sort arrays in JavaScript is to use the Array.prototype.slice() method to create a new array and sort it, like this:

Code 3 For slice().sort() Method In JavaScript

let names = ['John', 'Jane', 'Jim', 'Jill'];
let sortedNames = names.slice().sort();


['Jane', 'Jim', 'Jill', 'John']

This method creates a shallow copy of the original array and sorts it without affecting the original array.


If you liked this post Sorting Arrays In JavaScript, then please share this with your friends and make sure to bookmark this website for more awesome content.

If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Share on:

NK Coderz is a Computer Science Portal. Here We’re Proving DSA, Free Courses, Leetcode Solutions, Programming Languages, Latest Tech Updates, Blog Posting Etc.

Leave a Comment