ArticleZip > Lodash Orderby With Null And Real Values Not Ordering Correctly

Lodash Orderby With Null And Real Values Not Ordering Correctly

Have you ever encountered issues with sorting null and real values correctly when using Lodash's orderBy function? This common problem can be frustrating, but fear not, as we're here to guide you through resolving this issue.

Lodash is a powerful JavaScript library that provides a plethora of utility functions, including the handy `_.orderBy()` function for sorting arrays. One common challenge developers face is when sorting an array that contains both null and real values, as the default behavior of `orderBy` may not always produce the desired results.

To address this issue, we need to implement a custom comparison function that takes into account both null and real values. By defining a custom sorter, we can ensure that null values are handled appropriately during the sorting process.

Let's dig into the code and see how we can tackle this problem:

Javascript

const data = [
  { id: 1, name: 'Alice', age: 30 },
  { id: 2, name: 'Bob', age: null },
  { id: 3, name: 'Charlie', age: 25 },
  { id: 4, name: 'David', age: null },
];

const sortedData = _.orderBy(data, ['age'], [(val1, val2) => {
  if (val1 === null && val2 !== null) {
    return 1;
  }
  if (val1 !== null && val2 === null) {
    return -1;
  }
  return val1 - val2;
}]);

console.log(sortedData);

In this example, we have an array of objects representing individuals with names and ages. The `age` property can be either a number or null. To sort this array by age, we pass in a custom comparator function as the third argument to `orderBy`.

The custom comparator function first checks if either value is null and adjusts the sorting order accordingly. If both values are not null, a standard numerical comparison is performed.

By following this approach, you can ensure that null values are handled gracefully during sorting, preventing unexpected behavior in your application.

Next time you encounter issues with Lodash's `orderBy` not ordering null and real values correctly, remember to leverage a custom comparison function to tailor the sorting logic to your specific requirements.

Keep coding, stay curious, and happy sorting!