我有一个对象数组
说,
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'}
];
我需要按名称
按升序对数组进行排序如果数组具有未定义,则应将该对象推送到已排序列表的末尾。
预期输出
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'}
];
答案 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);