I have an array of objects
Say,
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'}
];
I need to sort the array in ascending by name
If the array has undefined, then that object should be pushed to the end of the sorted list.
Expected output
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With