Search code examples
arrayssortinglodash

How to check if value exist when using lodash sortBy?


I'm using lodash to sort an array, using this code:

this.employees = _.orderBy(this.employees, [employee => employee.acf.user_department.name], [order]);

It fails if there is no data for this value, so how can I check if the value exist / handle undefined values?

I'm trying to learn to use these fancy arrow functions, so it would be nice if an explanation could contain how to do it the ES6 way.


Solution

  • Use lodash's _.get() - it can iterate a path (the 2nd arg), and if part of the path is missing, instead of error you get undefined or the default value (3rd arg):

    _.get(employee, 'employee.acf.user_department.name', null)
    

    Example:

    const employee = {};
    
    const result = _.get(employee, 'employee.acf.user_department.name', 'I\'m the default'); // the 3rd param is a default value
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

    And in your sort method (default is empty string):

    this.employees = _.orderBy(this.employees, [employee => _.get(employee, 'employee.acf.user_department.name', '')], [order]);