包含未定义值的Javascript不区分大小写的排序对象

nij*_*jin 3 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'}
];
Run Code Online (Sandbox Code Playgroud)

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

  1. 该对象可能包含未定义名称
  2. 对象名称可能是大写和小写的混合(所以它必须是不区分大小写的搜索)

如果数组有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'}
];
Run Code Online (Sandbox Code Playgroud)

Ale*_* T. 7

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);
Run Code Online (Sandbox Code Playgroud)