Created
August 2, 2022 16:43
-
-
Save ahsanihsan/d87ab5249aeef9fa4a39080e7e838644 to your computer and use it in GitHub Desktop.
Array Element Occurence Snippet (Muhammad Ahsan)
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
const arrExample = [5,5,2,2,1] | |
let occurence = {} | |
arrExample.forEach((item) => { | |
if(Object.keys(occurence).includes(item.toString())){ | |
occurence[item] = occurence[item] + 1 | |
} else occurence[item] = 1 | |
}) | |
let greaterValue = 0 | |
let greaterKey = "" | |
Object.keys(occurence).map(item => { | |
if(occurence[item] >= greaterValue){ | |
greaterValue = occurence[item] | |
greaterKey = item | |
} | |
}) | |
console.log(greaterValue > 1 ? greaterKey : -1 ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment