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();
<p id="output"></p>