Sorting Method of Arrays in JavaScript

Sorting Method of Arrays in JavaScript

Understanding the Sort Method of Arrays

Understanding the Sort Method of Arrays. How to use JavaScript’s sort?

  • The JavaScript array sort() is used to sort array elements.
  • By default, the array will sort in ascending order, but we can change it.
  • This method willchange the original array.
  • We can also provide our comparing function to implement custom sorting.
var array = [1,2,3,1,2,3];

array.sort(); [1,1,2,2,3,3]

Let’s try another example:

var array = [1,2,11];

array.sort(); // [1,11,2]

For the above code, the expected result is [1,2,11], but we get [1,11,2]. The reason is the sort method converts the elements into strings then compares their sequences of UTF-16 code units values.

So the 11 is converted to “11”. When we compare two strings like “11” and “2”, the char code is compared means char code of 1 is 49 , whereas char code of 2 is 50. Because of 49 < 50, we get [1,11,2].

If the array contains any undefined, then all undefined elements are sorted to the end of the array. We can use the default sort method to sort strings.

var names = ["John", "Abu", "Babu", "Balu", "Antony"]


console.log(names); // ["Abu", "Antony", "Babu", "Balu", "John"]

For other types, we need to pass our compareFunction as an argument to sort Function. The compare function takes two arguments. The two arguments are taken as from array on index [0,1] , [1,2] … [arrayLength-2, arrayLength-1] for comparing the pair of elements.

The sorting of elements is based on the return value of compareFunction for each pair of comparison. If the function returns…

  • >0 then the position of a and b is swapped.
  • <=0 then there is no change in position

Let’s write a compare function to sort numbers.

function compare(a, b) {

  if (a < b ) {
    return -1;
  if (a > b ) {
    return 1;
  // otherwise a == b
  return 0;

// Now if we execute
var array = [2,1,11];

log(array); [1,2,11];

The above compare function can be simplified as:

function compareNumbers(a, b) {

  return a - b;

Because, when we do a-b, if a > b then it returns number > 0. If a<b, then it returns < 0. When a=b , then it returns 0.

To sort numbers in Descending Order, just change the a-b to b-a .

function Descending(a, b) {

    return b- a; 

Sorting Array of Objects

var users = [ {name: "John", age:20}, {name:"Antony" , age : 33}];

function sortByAge(obj1, obj2) {

    return obj1.age - obj2.age;

function sortByName(obj1, obj2) {


// output 
0: {name: "John", age: 20}
1: {name: "Antony", age: 33}



0: {name: "Antony", age: 33}
1: {name: "John", age: 20}

The **localeCompare()** method used in sortByName compareFunction returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

If the CompareFunction returns undefined, null, NaN, Infinity, then the array will not sort two members

var array = [3,2,1, 110, 102 , 30];

function customCompare(a, b){
   if(a > 10 || b > 10) {
      return Infinity;
   else {
      return a-b;


In the above example, we have defined if the a and b is less than 10 , it will sort by ascending order. Otherwise, the function will return Infinity, though Infinity > 0. But, it will not be swapped. This is the same for undefined, null, NaN.

Thank you for reading !

Advanced Programming in MATLAB Data Types and Data Structures

Advanced Programming in MATLAB Data Types and Data Structures

Get advanced level, in-depth knowledge of this fourth-generation, multi-paradigm numerical programming language. Learn the essential and unique MATLAB data types necessary for MATLAB programming and data analysis and how to use Cells, Tables, Time Tables, Structures and Map Containers.

Basic Course Description

MATLAB (matrix laboratory) is a multi-paradigm numerical computing environment and fourth-generation programming language which is frequenlty being used by engineering and science students. While teaching to students and observing different MATLAB related courses on Simpliv for more than six months now. I realized that there is a need for a course which should cover the key data types such as Cells, tables, time tables, structures and Map containers which should provide the students with the essential skills for taking full advantage of MATLAB strengths in data analysis and programming.

In this course we not only cover these data Types but also demonstrates different functions and operation and their conversions to make analysis and programming a greater experience.

The following are the outlines of this course.

Segment 1: introduction to the Course
Segment 2: Cell Data Type
Segment 3: Table Data Type
Segment 4: Time Table Data Type
Segment 5: Structures
Segment 6: Map Containers
Segment 7: Conversion between Different Data Types
Your Benefits and Advantages

You receive knowledge from a Ph.D. in Computer science with over 10 years of teaching and 15 years of programming experience and another decade of experience in using MATLAB
The instructor has 6 courses on simpliv on MATLAB including a best seller course
The overall rating in these courses are (4.5/5)
If you do not find the course useful, you are covered with 30 day money back guarantee, full refund, no questions asked!
You have lifetime access to the course
You have instant and free access to any updates i add to the course
You have access to all Questions and discussions initiated by other students
You will receive my support regarding any issues related to the course
Check out the curriculum and Freely available lectures for a quick insight
Student Testimonials!

This is the second Simpliv class on Matlab I've taken. Already, a couple important concepts have been discussed that weren't discussed in the previous course. I'm glad the instructor is comparing Matlab to Excel, which is the tool I've been using and have been frustrated with. This course is a little more advanced than the previous course I took. As an engineer, I'm delighted it covers complex numbers, derivatives, and integrals. I'm also glad it covers the GUI creation. None of those topics were covered in the more basic introduction I first took.

Jeff Philips

Great information and not talking too much, basically he is very concise and so you cover a good amount of content quickly and without getting fed up!

Oamar Kanji

The course is amazing and covers so much. I love the updates. Course delivers more then advertised. Thank you!

Josh Nicassio

Student Testimonials! who are also instructors in the MATLAB category

"Concepts are explained very well, Keep it up Sir...!!!"

Engr Muhammad Absar Ul Haq instructor of course "Matlab keystone skills for Mathematics (Matrices & Arrays)"

It's time to take Action!

Click the "Add to Cart" button at the top right now!

Time is limited and Every second of every day is valuable.

I am excited to see you in the course!

Best Regrads,

Dr. Nouman Azam

Who is the target audience?

Researchers, Entrepreneurs, Instructors, College Students, Engineers, Programmers, Simulators
Basic knowledge
General know how of MATLAB programming
What will you learn
The essential and unique MATLAB data types necessary for MATLAB programming and data analysis
At the end you can confidently use different data types and structures such as Cells, Tables, Time Tables, Structures and Map Containers
You will be able to convert between different data types
To continue:

Python Programming & Data Handling

Python Programming & Data Handling

Python Programming & Data Handling

Students will be able to know various commands include:

Python Basic Programming

string,if else,Range, for loop, while loop, making functions, tuple, dictionary etc


Download files from Web, Exceptional Handling etc

Data Handling:

Get data from files create , read, write, delete.


Image transformation , Image crop , edit and much more

Basic knowledge
Listener should know how about very basic C Language basic commands to understand Python Language
What will you learn
I will more update if any student want need to add more skills related to python

20 Things to Learn and Effective tips to becoming JavaScript Master

20 Things to Learn and Effective tips to becoming JavaScript Master

Do you want to get into web development? Or perhaps you’re fascinated with code and software? If so then JavaScript is a good choice for you. In this post, we will for you 20 things to learn and Simple Effective tips on the way to becoming a JavaScript Master


I guess you are a web developer. Hopefully you are doing fine and you have a great job, maybe you are even self-employed or working as a freelancer. Maybe you are just starting out as a web developer, maybe you have been working as a programmer for a longer period already.

However comfortable you are with JavaScript, it is always good to get a refresher on some topics to read up about or get them on the radar in the first place. Here are 10 things you definitely have to learn before you can call yourself a master in JavaScript.

1. Control Flow

Probably the most basic topic on the list. One of the most important, maybe the most important one. If you do not know how to proceed with your code, you will have a hard time. Knowing the ins and outs of basic control flow is definitely a must.

  • if else — If you don’t know these, how did you write code before?
  • switch — is basically if else in a more eloquent way, use it as soon as you have multiple of different cases.
  • for — Do not repeat yourself, this is what loops are for. Besides the normalfor -loop for of and for in come in very handy. The big advantage of for -loops is that they are blocking, so you can use async await in them.
  • Advanced conditionals — Using the ternary and logical operators can make your life a lot easier, especially when you try to do things inline, meaning that you don’t want to save values to use them later. Example:
// ternary
console.log(new Date().getHours() < 12 ? 'Good Morning!' : 'Time for a siesta')
// logical operators
const isJsMaster = prompt('Are you a JavaScript master?') === 'true'
console.log(isJsMaster && 'proficient coder')

2. Frontend Framework

The big three are React.js, Angular and Vue.js. If you are looking for a job nowadays, you will almost always have one of those listed as a prerequisite. Even if they change quite quickly, it is important to grasp the general concept of those to understand how applications work. Also, it is just easier to write apps that way. If you haven’t decided which train you want to jump on, my suggestions is React.js. I have been working with it for the last couple of years and did not regret my decision.

3. Asynchronity

This is a very important aspect of JavaScript, Either you are fetching data from the backend or you are processing requests asynchronously in the backend itself. In pretty much all usecases, you will encounter asynchronity and its caveats. If you have no idea what that is, you will probably get a weird error, which you will try to fix for a couple of hours. If you know what it is, but you don’t really know what to do about it, you will end up in callback-hell. The better approach is to use promises and/or async await in your apps.

4. Node.js / Express

Even as a frontend developer, you should know the basics of node.js. Ideally, you would also know how to spin up a simple express server and add some routes or change existing ones. JavaScript is great for writing scripts to help you automate a lot of tasks. Therefore, knowing how to read files, work with filepaths or buffers gives you a good toolset to build anything.

You may also like: Best Design Patterns for writing JavaScript Web applications

5. Error handling

This took a while for me. It does not matter if you are working on frontend or backend, the first year or so, you will probably default to console.log or maybe console.error for ‘handling’ errors. To write good applications, you definitely have to change that and replace your lazy logs with nicely handled errors. You may want to check out how to build your own Error constructor and how to catch them correctly, as well as showing the user what the actual problem is.

6. Data Models

Similar to moving through your application continuously, you have to decide where to group specific information chunks and where to keep them separate. This does not only apply to building database models, but also function parameters and objects or variables. Example:

const calcShape = (width, height, depth, color, angle) => {...}
const calcShape = ({width, height, depth, color, angle}) => {...}

7. DOM Manipulation

This is an interesting topic. Normally it is somewhat left out in the day today life as a developer. Maybe you learned jQuery and never felt the need to pick up some native DOM manipulation skills, maybe you are just using a frontend framework, where there is rarely a need for custom DOM manipulation. However, I think this is a crucial part of understanding JavaScript, at least in the frontend. Knowing how the DOM works and how to access elements gives you a deep understanding of how websites work. In addition, there will be the point where you have to do some custom DOM manipulation, even when you use modern frontend frameworks, and you definitely do not want to put jQuery in your package.json just to access an element.

8. Functional Approach

There is an everlasting debate about functional vs. object-oriented programming. You probably can achieve the same thing with both of the approaches. In JavaScript, it is even easier, you have both of the approaches available. Libraries like lodash give you a really nice collection of tools for building applications with a functional approach. Nowadays, it is not even necessary to use external libraries any more. A lot of the most important functions have been implemented in the official JavaScript specification. You definitely should know how to use map reduce filter forEach and find.

9. Object Oriented Approach

Similar to the functional approach, you also have to get familiar with object oriented JavaScript, if you want to master it. I neglected that part for a long time in my career and just worked my way through with a workaround, but sometimes it is definitely better to use objects/classes and instances to implement specific functionality. Classes are widely used in React, MobX or custom constructors.

10. Bundling / Transpilation

Unfortunately, this is a big part of web development. On the one hand I should not say unfortunate, because it is great to be able to write code with all the newest features. On the other hand, the reason why I’m saying that is that we always have to keep in mind that there’s older browsers around that may not support these features, therefore we have to transpile our code into something else that the old browsers understand. If you work with node.js, you will probably have less exposure to transpiling your code. The de-facto standard for transpilation is babel.js, so get familiar with it. As for bundling your code and tying everything together, you have a couple of options. Webpack was the dominant player for a long time. Some time ago, parcel popped up out of nowhere and is now my preferred solution, since it is so performant and easy to configure, although not perfect.

This is not specific to JavaScript, but incredibly helpful in a lot of use cases. Just as confusing as well. Getting to know the syntax of Regular Expressions definitely takes some time and remembering all of the different options is impossible.


Do you want to get into web development? Or perhaps you’re fascinated with code and software? If so then JavaScript is a good choice for you.

Why JavaScript?

Javascript is the scripting language of the internet and one of the most essential web technologies along with HTML and CSS. It’s a high-level, interpreted programming language that conforms to the ECMAScript specification. In more simplistic terms, it’s what allows you to implement and display complex things on your webpage, to create content, to animate images and tons of other amazing possibilities with just a few lines of code.

There’re plenty of reasons to learn this wonderful programming language. The most important one is the fact that JavaScript runs everything and everywhere. Most of the prominent websites are built on the backbone of JavaScript while currently there are more than 3 billion devices be it Smartphones or desktops. JavaScript went through a massive surge of popularity and quickly become the most dominant language in the world of software. In light of this, it’s obvious that Javascript skills are in high demand by companies everywhere. For all these reasons and more, it’s lucrative to have JavaScript skills on your resume.

Why is it challenging?

Learning JavaScript is easier said than done. Newcomers often run into similar kinds of problems such as difficulties in understanding confusing concepts. Not only that, but JavaScript also has an ever-changing tooling landscape one that makes it even far more grueling to understand. It’s hard to find the motivation to complete a demanding task such as this. JavaScript is also a vigorously un-typed language which means that the same thing in one code can easily mean something different depending on the context and medium. It also is extremely hard to debug due to a non-existent support system for different classes.

Tips for JavaScript Beginner

So the question is how to learn JavaScript? Similar to every complicated thing in life, you can learn JavaScript coding through constant practice and by never giving up. To help you in this task, we have written down the best way of learning this skill just for you! Try to follow these tips to enhance your learning experience.

1. Keep experimenting & Interact with veterans

Find and make your own way to solve problems related to JavaScript. Keep experimenting with the problems and what you have learned so far. Also, do interact with the veterans as the large community lead to more support and help you’ll be able to receive. Fortunately, JavaScript has one of the largest internet communities that is all about giving and receiving help and exploring the world of JavaScript. Take advantage of that! Meet up with the experts to not only motivate yourself to study but to learn as well. You might even be offered a mentorship! By being a part of a community, you’ll also be able to keep up to date with new, innovative tools!

2. Do not rush! Go step by step

I know it’s tempting to move on immediately once you understand a concept, but don’t! Instead, play with what you have learned, get comfortable and even combine it with the previous lessons. Start from beginner’s level and cover all the topics from tutorials, check resources, implement what you have learned and when you are finally confident of your beginner level skills, then move on to the intermediate level and after that, to advance level. By limiting the learning content and keeping in touch with the previous lessons, you’ll be able to retain the material in your head and find it easier to remember key concepts. The process seems long for sure but it actually takes far less time since you don’t have to keep revising and is actually quite fun. There’s really nothing that you cannot do with JavaScript in regards to web development.

3. Look out for JavaScript Resources

The internet has millions of sources available for you to use. Take “JavaScript: The Definitive Guide” by David Flanagan. It’s a book that has been forever considered a bible for JavaScript programmers across the world. In it is a comprehensive guide that is well-organized and detailed for new programmers to learn and old programmers to revise. Another book that you can read is “You Don’t Know JS: Up and Going” by Kyle Simpson which provides the necessary background for those with limited knowledge about programming. The entire series introduces more complex and harder parts of the JavaScript language as you read on one book at a time. Furthermore, there are tons of articles, blog posts and even YouTube videos available for reference. Don’t waste these valuable resources!

You may also like: Keeping your JavaScript code clean forever and scalable

4. Right attitude

The first thing you need to do is to go with the right attitude to learn JavaScript. Learning JavaScript is going to become needlessly more bothersome if you approach it with the wrong mindset. Trying to learn it with an “I need to get this over” mindset is not going to take you anywhere. It’s a huge struggle to face and you truly have to be passionate about code to learn it. Not only that, you need to remind yourself to have fun with what you’re learning as JavaScript code is capable of astonishing things once you get the hang of it.

5. Start Slowly

A mistake many beginners make is that they directly start working on frameworks such as jQuery, AngularJS, Backbone, etc. You should never do it. Instead, you should start working on DataTypes and in-built methods. After getting enough of the fundamentals, you can try NodeJS. Trust me, NodeJS is very simple, just a JavaScript code backed up with inbuilt libraries. Then, you can try frameworks.

6. Find the perfect editor for JavaScript

You can’t code without a text editor. Fortunately, you have tons of options to choose from. To write JavaScript code, you can either use your Windows notepad or even download programs such as Notepad++ or Visual Studio Code. Either way, after going through all possible editors, choose the one that you’re most comfortable to work on as this is where you’ll be spending most of your time. Also when you’re starting out, it’s essential to choose an editor that has a simplistic interface and will support you as a beginner.

7. JavaScript Tutorials!

If you search the web for JavaScript tutorials, there are a vast number of tutorials available online on sites such as CodeAcademy, FreeCodeCamp, etc. If you’re a beginner then you should start from beginner level JavaScript tutorials and then move on to intermediate and advanced level. Tutorials are like doing grammar exercises and the sites with JavaScript tutorials are ideal for learning the basics and getting used to the syntax. Learning JavaScript is no different than learning French or Spanish. It takes time.

8. Start Ajax and Async after getting a hang of the basics

After you have spent quite a lot of time on JavaScript, start working on Ajax and Async concepts. Learn how to use different functions on JavaScript and use classes as well. All of these things take quite a lot of time to master but trust me; all your hard work will surely be rewarded.

9. Challenge yourself! Explore JavaScript and learn

When it comes to learning JavaScript, there is always something you can learn as it is a never-ending process. A lot of people end up never improving their JavaScript coding by spending too much time only doing what they are confident about. Make sure that you’re not one of them. Every time you finish a lesson, ask yourself if you have learned something you didn’t know before. That is the key to success. Be mindful of what you want to learn or improve your knowledge of. Make sure that you’re challenging yourself and growing as a developer instead of conforming to a single comfort zone.

10. Keep yourself up to date and be prepared

JavaScript isn’t an easy skill to learn. If it was, it wouldn’t be held with the same reverence as it is in the labor market now. You need to understand the fact that learning JavaScript would require a huge amount of time and dedication. It’s not going to be an easy road. Not only is JavaScript already a complex and intricate skill to master, but it is also a growing field which would require you to stay updated with the new web development practices. Prepare yourself that it’s going to consume a majority of your time. Be patient too. You’re not going to learn JavaScript in a month and maybe not even in a year. All the time spent is going to be grilling, demanding but remember that it will also be completely worth the trouble.


Learning JavaScript is constant work and quite difficult but with the right attitude and determination, learning it can be an extremely satisfying experience. All you need is passion and a hunger to learn. Hopefully, with the above-mentioned tips, as well as the other brilliant and detailed materials available online, you’ll be able to grasp JavaScript as quickly as possible while also having a great enjoyable ride.

Hopefully you know all of the topics listed above already. If not, put in the work and try to become a master in JavaScript! It is definitely worth it. Remember that practicing is everything when it comes to coding, so even if you are not familiar with these concepts or know them but you don’t really know how to apply them, it will come in the future.

What do you think about the list? Is something missing? Do you think other topics are more important when coding? Let me know in the comments!

Thank for visiting and reading this post! I'm highly appreciate your actions! Please share if you liked it!