Skip to content

Instantly share code, notes, and snippets.

@rrmesquita
Last active August 18, 2019 02:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rrmesquita/3ff4cea73027cdbb8f373d9431cc160d to your computer and use it in GitHub Desktop.
Save rrmesquita/3ff4cea73027cdbb8f373d9431cc160d to your computer and use it in GitHub Desktop.
Get the most frequent element from array of objects
/**
* Filter an array of objects to get the most frequent element
*
* @param {Object[]} arr The array of objects
* @param {String} keyname The name that will be used to filter the objects
* @returns {Array}
*/
getMostFrequent(arr, keyname) {
// Store how many times each element appears
let lookup = {};
for (let i = 0; i < arr.length; i++) {
const key = arr[i][keyname];
if (lookup[key] === undefined) lookup[key] = 0; // Insert if not available yet
lookup[key]++;
}
// Transform that into an sortable array
let sortableLookup = [];
for (let o in lookup) {
sortableLookup.push([o, lookup[o]]);
}
// Sort the elements
let result = sortableLookup.sort((a, b) => b[1] - a[1]);
// Get one of the most frequent
let best = result[0];
// Filter by `keyname` to get the most frequent words
result = result.filter(el => el[1] === best[1]).map(el => el[0]);
return result;
}
@rrmesquita
Copy link
Author

feel free to improve this code. thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment