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
Create a counter of the array's elements using reduce:
arr.reduce(
(counter, key) => {counter[key] = 1 + counter[key] || 1; return counter},
{}
);
Sort the counter object using sort on Object.entries and finally show only keys.
const arr = ["apples", "oranges", "oranges", "oranges",
"bananas", "bananas", "oranges"
];
// create a counter object on array
let counter = arr.reduce(
(counter, key) => {
counter[key] = 1 + counter[key] || 1;
return counter
}, {});
console.log(counter);
// {"apples": 1, "oranges": 4, "bananas": 2}
// sort counter by values (compare position 1 entries)
// the result is an array
let sorted_counter = Object.entries(counter).sort((a, b) => b[1] - a[1]);
console.log(sorted_counter);
// [["oranges", 4], ["bananas", 2], ["apples", 1]]
// show only keys of the sorted array
console.log(sorted_counter.map(x => x[0]));
// ["oranges", "bananas", "apples"]