Javascript Case Insensitive对包含未定义值的对象进行排序

时间:2014-11-20 09:48:08

标签: javascript arrays sorting

我有一个对象数组

说,

var fruits = [
   {name:'apple', capital:'sample'},
   {name:'Tomato', capital:'sample'},
   {name:'jack fruit', capital:'sample'},
   {name:undefined, capital:'sample'},
   {name:'onion', capital:'sample'},
   {name:'Mango', capital:'sample'},
   {name:'Banana', capital:'sample'},
   {name:'brinjal', capital:'sample'}
];

我需要按名称

按升序对数组进行排序
  1. 该对象可能包含名称
  2. 中的未定义
  3. 对象名称可能是大写和小写的混合(所以必须是一个案例 不敏感的搜索)
  4. 如果数组具有未定义,则应将该对象推送到已排序列表的末尾。

    预期输出

    var fruits = [
       {name:'apple', capital:'sample'},
       {name:'Banana', capital:'sample'},
       {name:'brinjal', capital:'sample'},
       {name:'jack fruit', capital:'sample'},
       {name:'Mango', capital:'sample'},
       {name:'onion', capital:'sample'},
       {name:'Tomato', capital:'sample'},
       {name:undefined, capital:'sample'}
    ];
    

1 个答案:

答案 0 :(得分:3)

fruits.sort(function (a, b) {
  // for all false values null, false, '', 0, and so on 
  //if (!a.name) return 1;
  //if (!b.name) return 0;

  // only for undefined 
  if (typeof (a.name) === 'undefined') return 1;
  if (typeof (b.name) === 'undefined') return 0;

  a = (a.name || '').toLowerCase();
  b = (b.name || '').toLowerCase(); 

  return (a > b) ? 1 : ((a < b) ? -1 : 0);
});

console.log(fruits);

DEMO:http://jsbin.com/hugise/3/