Friday, August 10, 2018

Sort an array so that null values always come last Jquery

var arr = [ null, 'a', 'b', null, 'd'];
    
    var alphabetically = function(ascending){
      
      return function(a,b){ 
      
        if(a === null){
          return 1;
        }
        else if(b === null){
          return -1;
        }
        else if(a === b){
          return 0;
        }
        else if(ascending) {
          return a < b ? -1 : 1;
        }
        else if(!ascending) {
          return a < b ? 1 : -1;
        }
      };
    }
    
    console.log( arr.sort(alphabetically(true)) );
    console.log( arr.sort(alphabetically(false)) );
OR  below code worked for me
arr.sort(function(a, b) {
    return (a===null)-(b===null) || +(a>b)||-(a<b);
});
             IN C# USING LINQ 
List<Student> studentList = new List<Student>() { new Student() { StudentID = null, StudentName = "John", Age = 18 } , new Student() { StudentID = 2, StudentName = "Steve", Age = 15 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } , new Student() { StudentID = null, StudentName = "Ram" , Age = 20 } , new Student() { StudentID = 5, StudentName = "mohan" , Age = 20 } , new Student() { StudentID = null, StudentName = "kishan" , Age = 18 } , new Student() { StudentID = null, StudentName = "rajesh" , Age = 19 } }; var testing=studentList.Select(k=>k).OrderBy(c => c.StudentID.HasValue ? (c.StudentID == 0 ? (int.MaxValue - 1) : c.StudentID) : int.MaxValue) .ToList();
                         IN SQLSERVER USING LINQ 
select *
from employee
order by case when UpdatedDate is null then 1 else 0 end, UpdatedDate

No comments:

Post a Comment

javascript Filter/index off

 var family = [{"name":"Jack",  "age": 26},               {"name":"Jill",  "age"...