-1

Consider this array.

[1, 2, 2, 2, 3, 4, 4, 5] 

I would like to sort this array in the order of how many times a certain element value exist. So in the case above the value 2 exist three times, therefore these should come first. Followed by the two instances of 4, and then last 1, 3, 5.

[2, 2, 2, 4, 4, 1, 3, 5] 
Anders Östman
  • 3,702
  • 4
  • 26
  • 48

2 Answers2

2

Ok only hints. take a hashmap, put the count against each item and when you have count for each element sort it accordingly and REBUILD the array.

  • he is working in javascript , so there is nothing called hashmap – Panther Dec 08 '14 at 13:01
  • @Panther: No, but it's frequently used in the generic. And of course, ES6 will have [`Map`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-map-constructor), so we don't have to worry about using `hasOwnProperty` or playing games to avoid accidentally using `toString` as a key. :-) – T.J. Crowder Dec 08 '14 at 13:02
  • http://stackoverflow.com/questions/368280/javascript-hashmap-equivalent – Ankit Srivastava Dec 08 '14 at 13:03
  • @T.J.Crowder thanks, i was not aware of Map in javascript. Tiger Scott has resolved the problem. – Panther Dec 08 '14 at 13:05
  • @TigerScott thanks , i beleive then this is resolved – Panther Dec 08 '14 at 13:07
2

Here's how I'd probably do it:

  1. Loop through the array building a map (just a plain object for now, since we don't have ES6's Map yet) with property names for the numbers (2 and so on), where that property's value is the number of times that number appears in the array. (E.g., during the loop, add one to the value if we've seen that number before; if we haven't, start with 1.)

  2. Once I had the map, I'd use Array#sort to do the sort, giving it a comparator function that returns the result based on the number of times each of the two values given to the function has appeared. (It's okay if we end up comparing 2's count with 2's count, the result will be 0 and they'll be considered even.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks! This seems doable =) – Anders Östman Dec 08 '14 at 13:03
  • You provided me with an great answer from which I could create a working solution. But you still think it's unclear what I'm asking about? Please give me some tips of how you think I should rephrase my question. I would not mind delete the question if it doesn't meet the SO standards. – Anders Östman Dec 08 '14 at 15:56
  • @AndersÖstman: Have a kick around the [help]. Basically, in general it's best to take a swing at things first, say what you've tried and why you're unhappy with it, and then ask for help. But I'm glad that this was "great." Perhaps if it's algorithm input you're asking for, you might highlight that next time (as we get ***so many*** questions which are basically asking for code -- whereas your reactions to the answers suggests that wasn't what *you* were doing.) – T.J. Crowder Dec 08 '14 at 16:49