Computer >> Computer tutorials >  >> Programming >> Javascript

Sorting an array that contains undefined in JavaScript?


Let’s say the following is our array with string values and even undefined −

var studentNames = ["Mike", undefined, "Adam", "Bob", undefined, "Carol"];

Use sort() to sort the above array.

Example

Following is the code −

var studentNames = ["Mike", undefined, "Adam", "Bob", undefined, "Carol"];
var sortingInAscendingOrder = (first, second) => {
   if (first === "") return 1;
   if (second === "") return -1;
   return first.localeCompare(second);
};
studentNames.sort(sortingInAscendingOrder);
console.log(studentNames);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo275.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo275.js
[ 'Adam', 'Bob', 'Carol', 'Mike', undefined, undefined ]