Sort an array so that null values always come last

前端 未结 8 2205
轮回少年
轮回少年 2020-11-28 05:46

I need to sort an array of strings, but I need it so that null is always last. For example, the array:

var arr = [a, b, null, d, null]

When

相关标签:
8条回答
  • 2020-11-28 06:45

    I am sorting objects with a custom index and this works for me. I am not wanting to change the original array and it is important to keep the null indexes where they are.

    let sorted = [...array].sort((a, b) => {
                   if (!a || !b) return 0;
                   else return a.CustomIndex - b.CustomIndex;
                 });
    
    0 讨论(0)
  • 2020-11-28 06:49

    Do it like:

            var arr = [a, b, null, d, null]
    
            foreach ($arr as $key => $value) {
               if($value == null)
               unset($arr[$key]);
               $arr[] = $value;
    
            }
            // rebuild array index
            $arr = array_values($arr);
    
            echo '<pre>';print_r($arr);die;
    
    0 讨论(0)
提交回复
热议问题