Sorting an array that contains undefined in JavaScript?

In JavaScript, arrays can contain undefined values which require special handling during sorting. By default, the sort() method converts all elements to strings, placing undefined values at the end of the sorted array.

Let's explore different approaches to sort arrays containing undefined values effectively.

Default Behavior with sort()

When using the basic sort() method on arrays with undefined, JavaScript automatically places undefined values at the end:

<!DOCTYPE html>
<html>
<body>
   <script>
      var namearr = ["Zebra", "Yatch", undefined, "Egg", undefined];
      namearr.sort();
      console.log(JSON.stringify(namearr));
   </script>
</body>
</html>
["Egg","Yatch","Zebra",null,null]

Using Custom Compare Function for Ascending Order

To handle undefined values explicitly and ensure proper string sorting, use a custom compare function:

<!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);
      });
      console.log(JSON.stringify(arrname));
   </script>
</body>
</html>
["Dog","Frog",null,null]

Sorting in Descending Order

For descending order with undefined values placed at the end:

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

Sorting Objects with Undefined Properties

When sorting arrays of objects that may have undefined properties:

<!DOCTYPE html>
<html>
<body>
   <p id="result"></p>
   <script>
      const data = [
         { name: 'BMW', rating: undefined },
         { name: 'BENZ', rating: 11.34 },
         { name: 'RX100', rating: 8.5 }
      ];
      
      data.sort((x, y) => {
         const xRating = x.rating || 0;
         const yRating = y.rating || 0;
         return yRating - xRating;
      });
      
      document.getElementById("result").innerHTML = JSON.stringify(data);
   </script>
</body>
</html>
[{"name":"BENZ","rating":11.34},{"name":"RX100","rating":8.5},{"name":"BMW"}]

Key Sorting Strategies

Method undefined Placement Best For
Default sort() End of array Simple string sorting
Custom compare function Configurable Complex sorting logic
Fallback values Treated as specified value Numerical sorting

Conclusion

When sorting arrays with undefined values, use custom compare functions to handle undefined explicitly. JavaScript's default behavior places undefined at the end, but custom functions give you full control over sorting logic.

Updated on: 2026-03-15T23:19:00+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements