An array function that returns an array containing all elements appearing a certain number of times Array.prototype.itemsWithQuantity = function(n) {
    var counts = {};
    var result = [];
    var i = this.length;
    while(i--){
        counts[this[i]] = counts[this[i]] == undefined ? 1 : counts[this[i]] + 1;       
    }
    i = this.length;
    var alreadyPushed = {};
    while(i--){
        if(counts[this[i]] == n &amp;&amp; !alreadyPushed[this[i]]){
            alreadyPushed[this[i]] = true;
            result.push(this[i]);
        }       
    }
    return result;
};


Above is my function that returns all the items in an array with a certain quantity. E.g., [1,2,3,2,3,4].itemsWithQuantity(2) == [2,3].

Not only is the code kinda ugly, but I also have a feeling there's a more efficient way to do it that I'm not spotting.
I guess you could use Array.forEach() to do the counting and laterArray.filter() to get the elements with the desired number of occurences.

It reduces the bookkeeping to the minimum of counts, goodbye alreadyPushed. It also reduces the boilerplateness a little, by giving you local variables implicitely:


You have this[i] everywhere, which can look a little cryptic. You could store it in a local var element = this[i]; which could be considered more readable.
in my suggested code, you get those local variables as a result of using functions that receive the value as a parameter which you can of course name however you want.


I think it depends on how much you are used to seeing certain patterns show up in code. After doing it for a while, you know that

var i = this.length;
while(i--){ //...}


will iterate over all the elements. Array.forEach() calls it by its name, which can improve readability.

I had my first ever go at the built in scripting thingy here on stackexchange, take a look and try the code:



Array.prototype.itemsWithQuantity = function(n) {
  var counts = {};

  // count
  this.forEach(function(element) {
    counts[element] = counts[element] == undefined ? 1 : counts[element] + 1
  });

  // return those elements (which are the keys(=property names) of the object) occuring n times
  return Object.keys(counts).filter(function(element) {
    return counts[element] == n;
  });
};

var input = [1, 2, 3, 3, 4, 1, 2, 5];
var output = input.itemsWithQuantity(2);

document.getElementById("output").innerHTML = output.toString();
&lt;p id="output"&gt;&lt;/p&gt;