我有一个对象数组
说,
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 升序排列数组
- 对象的name中可能包含undefined
- 对象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'}
];
最佳答案
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);
关于Javascript Case Insensitive Sort objects containing undefined 作为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27036369/