Home > Software design >  Counting occurrences and frequency of elements in an array and sort them
Counting occurrences and frequency of elements in an array and sort them

Time:07-21

I have input array as follows. I want to get the unique occurrences name and frequency of those occurrences. I am able to achieve that as shown below.

let input = ["apple", "orange" , "pear", "orange", "apple", "orange"];
input.reduce(function (acc, curr) {
  return acc[curr] ?   acc[curr] : acc[curr] = 1, acc
}, {});

Result:

{ "apple": 2, "orange": 3, "pear": 1}

But I am expecting the result to be in ascending order of frequencies as shown below. Can someone let me know how to achieve it. Also, I have used function above. Can someone let me know how to use it with arrow operator (ES8 feature)

Expected Result:

{ "orange": 3, "apple": 2, "pear": 1 }

CodePudding user response:

You can convert the unsorted object, which is not sortable, to an array, which is sortable, and then back to an object:

let input = ["apple", "orange" , "pear", "orange", "apple", "orange"];
const unsorted = input.reduce(function (acc, curr) {
  return acc[curr] ?   acc[curr] : acc[curr] = 1, acc
}, {});

const sorted = Object.entries(unsorted) // converts to array of key/value pairs
    .sort(([,a],[,b]) => b - a) // sort descending (switch a and b to sort in reverse order)
    .reduce((r, [k, v]) => ({ ...r, [k]: v }), {}); // reduce back to object
console.log(sorted)

CodePudding user response:

You can use ObjectFromEntries along with Object.entries to sort it

const input = ["apple", "orange", "pear", "orange", "apple", "orange"];
const mapped = input.reduce((acc, curr) => {
  return acc[curr] ?   acc[curr] : acc[curr] = 1, acc
}, {});

const sorted = Object.fromEntries(Object.entries(mapped).sort(([, a], [, b]) => b - a));

console.log(sorted);

  • Related