【问题标题】:Javascript Case Insensitive Sort objects containing undefined as valueJavascript不区分大小写对包含未定义值的对象进行排序
【发布时间】:2015-01-18 02:58:10
【问题描述】:

我有一个对象数组

说,

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'}
];

我需要按 name 对数组进行升序排序

  1. 对象的名称中可能包含undefined
  2. 对象name可能是大写和小写的混合(所以一定是大小写 不敏感搜索)

如果数组有undefined,那么该对象应该被推到排序列表的末尾。

预期输出

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'}
];

【问题讨论】:

    标签: javascript arrays sorting


    【解决方案1】:

    const fruits = [
       { name: 'apple', capital: 'sample' },
       { name: 'Tomato', capital: 'sample' },
       { name: 'jack fruit', capital: 'sample' },
       { name: undefined, capital: 'sample' },
       { name: undefined, capital: 'sample' },
       { name: undefined, capital: 'sample' },
       { name: 'onion', capital: 'sample' },
       { name: 'Mango', capital: 'sample' },
       { name: 'Banana', capital: 'sample' },
       { name: 'brinjal', capital: 'sample' }
    ];
    
    const res = fruits.sort(function (a, b) {
      if (a.name === undefined) return 1;
      if (b.name === undefined) return -1;
      if (a.name === b.name) return 0;
      return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1;
    });
    
    console.log(res);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-11
      • 2011-01-30
      • 2011-12-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 2010-10-22
      • 1970-01-01
      相关资源
      最近更新 更多