简体   繁体   中英

counting occurrences and frequency of elements in an array and sort them using javascript

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 }

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)

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM