Sort a Javascript Array by frequency and then filter repeats

Viewed 24344

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", "oranges", "oranges", "bananas", "bananas", "oranges"]

becomes

["oranges, "bananas", "apples"]

8 Answers

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);}},{}))

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"]

Related