Spherical forums

Sphere Development => Sphere Support => Script Support => Topic started by: Harry Bo21 on May 25, 2013, 02:13:57 pm

Title: Alphabetical sort
Post by: Harry Bo21 on May 25, 2013, 02:13:57 pm
Anyone got a fast and effective function to sort an array by alphabetical order of one of its properties. In this case ".name"?
Title: Re: Alphabetical sort
Post by: Radnen on May 25, 2013, 04:45:15 pm
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

Code: (javascript) [Select]

function alphasort(a, b) {
  return a.name > b.name;
}

list.sort(alphasort);
Title: Re: Alphabetical sort
Post by: alpha123 on May 25, 2013, 05:49:16 pm
Radnen: Array#sort expects an integer from the callback function, so I think you want something like

Code: (javascript) [Select]
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.
Title: Re: Alphabetical sort
Post by: Harry Bo21 on May 25, 2013, 05:57:00 pm
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"
Title: Re: Alphabetical sort
Post by: alpha123 on May 26, 2013, 01:55:31 pm

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.

Quote

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.
Title: Re: Alphabetical sort
Post by: Harry Bo21 on May 26, 2013, 02:19:33 pm
Ouch, nice