Anyone got a fast and effective function to sort an array by alphabetical order of one of its properties. In this case ".name"?
See comparing strings: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String
and array sorts: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort
function alphasort(a, b) {
return a.name > b.name;
}
list.sort(alphasort);
Radnen:
Array#sort expects an integer from the callback function, so I think you want something like
function alphabeticalBy(key) {
return function (a, b) {
if (a[key] == b[key]) return 0;
return a[key] > b[key] ? 1 : -1;
};
}
array.sort(alphabeticalBy('name'));
HarryBo21: Consider Googling for this sort of basic JavaScript thing.
I did but kept getting lost in half the useless crap you come across.
Plus things were quiet here and we have empty forums. Thought itd be handy to have some basic topics there for the newbies to "search"
I did but kept getting lost in half the useless crap you come across.
...I just Googled for "javascript sort array alphabetically by key" and the
first (http://stackoverflow.com/questions/6712034/javascript-sort-array-by-firstname-alphabetically) result is
exactly what you're looking for.
Plus things were quiet here and we have empty forums. Thought itd be handy to have some basic topics there for the newbies to "search"
Newbies don't search, unfortunately they just ask. That's how you can tell a n00b from a real developer, is the n00b asks questions that are easy to Google for.
Maybe we should add a "Read this first" topic that gives pointers on how to search Google for common JavaScript problems, and only ask if they can't find it. We should include a link to StackOverflow (http://stackoverflow.com/), which is a far better place to ask not-Sphere-specific questions.
Also I fail to see what benefit you expect to gain from having basic topics which already exist in great quantities on the internet at large also here on the forums. Better to just link to StackOverflow or a search engine.
Ouch, nice