当字段的值可以为null时,对javascript数组进行排序?

时间:2016-03-18 04:12:51

标签: javascript

我有这个功能:

tests.sort(function (a, b) {
   var diff = a.title.localeCompare(b.title);
   return diff == 0 ? b.modifiedDate.localeCompare(a.modifiedDate) : diff;
});

我用它来tests数组先排序title然后排序modifiedDate。代码正在运行,但现在我发现它给出了一个错误。 当modifiedDate为null并且发生这种情况时,比较失败。

我怎么能这样做,以便如果modifiedDate为null,那么排序仍然有效,并将那些行放在具有modifiedDate但不为空的行之后?

2 个答案:

答案 0 :(得分:1)

从头脑中思考,按标题排序,然后 modifiedDate 排序为空:

tests.sort(function (a, b) {
   var diff = a.title.localeCompare(b.title),
       has_modifiedDate = a.modifiedDate && b.modifiedDate && true || false; 


  if (diff === 0) {
    if (has_modifiedDate) {
      return a.modifiedDate.localeCompare(b.modifiedDate)
    }
    else {
      if (! b.modifiedDate){
        if (! a.modifiedDate)
          return 0;
        else
          return -1;
      }
      else {
        if (! a.modifiedDate)
          return 1;
        else
          return -1;
      }
    }
  }
  else 
    return diff;
});

注意:这是未经测试的,而且这里很晚/很早。如果这不正确,请发帖,我将删除或更新;但是厌倦思考的方式。

您可以尝试使用的快速数据集;填写您想要的任何数据:

var tests = [
  {modifiedDate:'z',    title:'foo'},
  {modifiedDate:'a',    title:'foo'},
  {modifiedDate:null,   title:'foo'},
  {modifiedDate:'a',    title:'foo'},
  {modifiedDate:'null', title:'foo'},
  {modifiedDate:'z',    title:'foo'},
  {modifiedDate:'z',    title:'bar'},
  {modifiedDate:'a',    title:'bar'},
  {modifiedDate:null,   title:'bar'}
 ];

答案 1 :(得分:0)

试试这个:

C:\Users\S_programmer\AppData\Local\Android\sdk2\tools\emulator.exe -netdelay none -netspeed full -avd Nexus_5_API_21_x86
emulator: device fd:640
HAXM is not working and emulator runs in emulation mode
emulator: The memory needed by this AVD exceeds the max specified in your HAXM configuration.
emulator: AVD      RAM size = 1536 MB
emulator: HAXM max RAM size = 1024 MB
emulator: You might want to adjust your AVD RAM size and/or HAXM configuration to run in fast virt mode.
creating window 43 59 329 583
emulator: emulator window was out of view and was recentered
emulator: UpdateChecker: skipped version check