Sorting an array that contains undefined in JavaScript?


In JavaScript Arrays are used to hold several values in a single variable. When opposed to a variable, which can hold only one value, this Each element of an array has a number associated with it called a numeric index that enables access to it. Arrays in JavaScript begin at index zero and can be modified using a number of different techniques.

Let's take a look at the general case of sorting an array that contains undefined in JavaScript. The array is given below −

var namearr = ["Zebra", "Yatch", undefined, "Egg", undefined];

For sorting the array that was containing undefined in JavaScript can be done by using sort() method. When we apply the sort() method to the array, it will display the following output −

Var namearr=[“Egg”,”Yatch”,”Zebra”,undefined,undefined];

Let’s dive into the article for getting better understanding on how to sort an array that contains undefined in JavaScript.

Using sort() in JavaScript

The sort() method sorts an array's items while they are still in the array and then returns a reference to the newly sorted array. Since the items are transformed into strings, the default sort order is ascending.

Syntax

Following is the syntax for sort()

sort() // Functionless
sort((a, b) => { /* … */ } ) // Arrow function
sort(compareFn) // Compare function
sort(function compareFn(a, b) { /* … */ }) // Inline compare function

For getting more idea on sorting an array that contains undefined in JavaScript. Let’s have a look on the following examples.

Example

In the following example, we declare an array with an undefined value and then use the sort() method to sort the array, which displays the values first and then undefined in the array.

<!DOCTYPE html>
<html>
   <body>
      <script>
      var arrname = ["Frog", undefined, "Dog", undefined];
      arrname.sort(function(a, b) {
         if (a == undefined) {
            a = ""
         }
         if (b == undefined) {
            b = ""
         }
         return a.localeCompare(b);
      });
      document.write(JSON.stringify(arrname));
      </script>
   </body>
</html>

When the script gets executed, it will generate an output consisting of an array that was sorted in ascending order, displaying "values" first, followed by "undefined" in itself on the webpage due to an event that gets triggered on running the script.

Example

Consider the following example, here we are running the script by declaring an array along with undefined values in the array later, we are using the sort() method to sort the array from high value to low value, followed by undefined values at the end.

<!DOCTYPE html>
<html>
   <body>
      <script>
         const arr = ['yatch', undefined, undefined, 'bus'];
         const sortdescending = arr.sort((a, b) => {
            if (a === null) {
               return 1;
            }
            if (b === null) {
               return -1;
            }
            if (a === b) {
               return 0;
            }
            return a < b ? 1 : -1;
         });
         document.write(JSON.stringify(sortdescending));
      </script>
   </body>
</html>

On running the above script, the output window will pop up, displaying an array sorted from high value to low value, along with an undefined value at the end caused by an event.

Example

Execute the below code to check how the sort() method helped in sorting an array that contained an undefined value.

<!DOCTYPE html>
<html>
   <body>
      <p id="tutorial"></p>
      <script>
         data = [{
            car: 'BMW',
            rating: 'undefined'
         }, {
            bike: 'BENZ',
            rating: 11.34,
            jobTitle: 'engineering'
         }, {
            vehicle: 'RX100',
            rating: 11.34,
            jobTitle: 'mechanic'
         }, ];
         data.sort((x, y) => {
            if (x.jobTitle && y.jobTitle) {
               return (x.rating || 0) - (x.rating || 0);
            } else if (x.jobTitle || y.jobTitle) {
               return !(x.jobTitle) - !(y.jobTitle)
            } else {
               return (y.rating || 0) - (y.rating || 0);
            }
         });
         document.getElementById("tutorial").innerHTML = JSON.stringify(data);
      </script>
   </body>
</html>

When the script gets executed, the event gets triggered and displays an array that was sorted in ascending order, displaying the values first, followed by the undefined value at the end of the array on the webpage.

Updated on: 21-Apr-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements