Last active
August 18, 2019 02:02
-
-
Save rrmesquita/3ff4cea73027cdbb8f373d9431cc160d to your computer and use it in GitHub Desktop.
Get the most frequent element from array of objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
feel free to improve this code. thank you