Skip to main content

News

Topic: Alphabetical sort (Read 3145 times) previous topic - next topic

0 Members and 1 Guest are viewing this topic.
Alphabetical sort
Anyone got a fast and effective function to sort an array by alphabetical order of one of its properties. In this case ".name"?

  • Radnen
  • [*][*][*][*][*]
  • Senior Staff
  • Wise Warrior
Re: Alphabetical sort
Reply #1
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);
  • Last Edit: May 25, 2013, 06:50:27 pm by Radnen
If you use code to help you code you can use less code to code. Also, I have approximate knowledge of many things.

Sphere-sfml here
Sphere Studio editor here

Re: Alphabetical sort
Reply #2
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.

Re: Alphabetical sort
Reply #3
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"

Re: Alphabetical sort
Reply #4

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 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, 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.
  • Last Edit: May 26, 2013, 01:59:17 pm by alpha123

Re: Alphabetical sort
Reply #5
Ouch, nice