Reputation: 1401
Hello everyone I need a function so that i can sort an array of objects alphabeticaly by a certain property value.
Let say i have this array:
var myObj = [{Name: 'John'},
{Name: 2.10},
{Name: 'Andrew'},
{Name: 10},
{Name: 2.101}
];
The result should be 2.10, 2.101, 10, 'Andrew', 'John'. I need this sorting beacause in my program the Name property can be either a name as 'John' or and IP (like 1.0.0.14) or even a MAC address(97948453855)...
I have managed some sorting but it doesnt seem to work perfectly for both strings and numbers.
Thank you!
Upvotes: 0
Views: 584
Reputation: 386550
You could check for string and use the delta as first result part, or take the nummerical delta or at last the string comparison.
var array = [{ Name: 'John' }, { Name: 2.10 }, { Name: 'Andrew' }, { Name: 10 }, { Name: 2.101 }];
array.sort(function (a, b) {
return (typeof a.Name === 'string') - (typeof b.Name === 'string') || a.Name - b.Name || a.Name.localeCompare(b.Name);
});
console.log(array);
Upvotes: 3