What is an elegant way to take a javascript array, order by the frequency of the values, and then filter for uniques?
So,
[\"apples\", \"oranges\", \"o
Let me put a minimal code to get unique values (and with frequencies) in ES6.
var arr = ["apples", "oranges", "oranges", "oranges", "bananas", "bananas", "oranges"];
console.log([...new Set(arr)])
It is also applied to array of objects to aggregate some properties.
var arr = [{"fruit":"apples"}, {"fruit":"oranges"}, {"fruit":"oranges"}, {"fruit":"oranges"}, {"fruit":"bananas"}, {"fruit":"bananas"}, {"fruit":"oranges"}];
console.log(arr.reduce((x,y)=>{if(x[y.fruit]) {x[y.fruit]++;return x;} else {var z={};z[y.fruit]=1;return Object.assign(x,z);}},{}))
// returns most frequent to least frequent
Array.prototype.byCount= function(){
var itm, a= [], L= this.length, o= {};
for(var i= 0; i<L; i++){
itm= this[i];
if(!itm) continue;
if(o[itm]== undefined) o[itm]= 1;
else ++o[itm];
}
for(var p in o) a[a.length]= p;
return a.sort(function(a, b){
return o[b]-o[a];
});
}
//test
var A= ["apples","oranges","oranges","oranges","bananas","bananas","oranges"];
A.byCount()
/* returned value: (Array) oranges,bananas,apples */