티스토리 뷰

 

Today, I want to share a powerful solution that I discovered while working with AngularJS's `orderBy` filter. Sorting lists is a common task in web development, and AngularJS offers a convenient `orderBy` filter to handle it. However, I stumbled upon a challenge when dealing with null or empty values during sorting. In AngularJS, orderBy filter doesn't provide a straightforward way to handle null or empty values in a special way, such as placing them at the end of the list. However, we can workaround this by creating a custom filter function. This custom function will separate the list into two arrays, sort both arrays, and then concatenate them.


Here's a simplified version of the custom sorting function:

function customSort(itemList) {
    var withTheData = [];
    var nullData = [];

    for (var i = 0; i < itemList.length; i++) {
        if (itemList[i].orderKey !== null && itemList[i].orderKey !== undefined) {
            withTheData.push(itemList[i]);
        } else {
            nullData.push(itemList[i]);
        }
    }

    withTheData.sort(sortFunction);
    nullData.sort(sortFunction);

    return withTheData.concat(nullData);
}
}

In the code above, we define the `customSort` function, which takes an `itemList` as its argument. Inside the function, we declare two arrays: `withTheData` to store items with valid `orderKey`, and `nullData` to store items with null or undefined `orderKey`.

Next, we loop through the `itemList` and separate the items based on whether they have a valid `orderKey` or not. If the `orderKey` is neither null nor undefined, we push the item into `withTheData`; otherwise, we push it into `nullData`.

After that, we sort both arrays using a custom sorting function called `sortFunction`. This function allows you to implement your specific sorting logic. In this example, we sort the items by 'Name', assuming 'Name' is a property of the items.

Finally, the function returns the concatenated result of `withTheData` and `nullData`, ensuring that items with null or undefined `orderKey` appear at the end of the sorted list.

With this custom sorting function, you can now easily manage null or empty values in your AngularJS projects and get the exact sorting you want. 


Happy coding and happy sorting!