-2

Possible Duplicate:
How to sort an array of javascript objects?

Every time I mess with writing my own quicksort it ends up taking a lot longer than I initially thought. I've got a pretty small array but would still like to have a quicksort handy.

Something like

quicksort(myObjectArray) {
    //myObject[i].key is what the sort is done on
}

I actually did Google this so if you post a link to any of the first three or four pages on Yahoo or Google complete with obviously incomplete code else why would I be asking here... then you are wasting your life away trolling on stackoverflow and not actually answering anything.

Community
  • 1
  • 1
anonymous
  • 1,259
  • 2
  • 10
  • 15
  • 1
    Wait, there doesn't exist a Quicksort script on the internet? *** Check out the results on Stack Overflow: http://stackoverflow.com/search?q=[javascript]+quicksort – Šime Vidas May 10 '12 at 15:05
  • 5
    Any reason why you not use the built-in `sort` method with a callback? – Felix Kling May 10 '12 at 15:06
  • I believe that `Array.prototype.sort` will be `O(n log n)`, so you'll just have to supply the comparator function that takes `key` into account. – Imp May 10 '12 at 15:06
  • Although according to MDN the sort is stable, so it is probably not quicksort, but maybe heap or merge... – Imp May 10 '12 at 15:08
  • 1
    Next time, try searching for a solution to the the problem you are trying to solve, instead of a solution to a solution. Google: "how do I sort an array of javascript objects". – mikerobi May 10 '12 at 15:10
  • array.sort( ) works for an array of objects, but it is extremely slow when your array is very big. I was testing it on an array with 2000 elements and it takes about 4 minutes to sort – Sadaf Fara Jan 27 '22 at 08:57

1 Answers1

5

Just use .sort:

myObjectArray.sort(function(a,b){
    // handle .key here depending on your application
});

Examples:

http://www.sitepoint.com/sophisticated-sorting-in-javascript/

Jerod Venema
  • 44,124
  • 5
  • 66
  • 109
  • You win this round stackoverflow. Here is what I ended up with. Seems to be working. function sortObjectArray(objectArray, key) {objectArray.sort(function(a, b) {return a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0;}); } – anonymous May 10 '12 at 16:04