Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript hash on a set of numbers

I need to get a frequency on a set of numbers and do some work on the "key" of the frequency, like check if the keys (as numbers) are consecutive. I am surprised that the key are of type "string". Is there a way to make the keys have type "number"?

of course, I can compare two keys like if (parseInt(k2) == (parseInt(k1) + 1)), but that’s awkward.

Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let freq = {} //frequency
let nums = [1,2,3]
nums.forEach(n => {
    if (freq[n] === undefined) {
        freq[n] = 1
    } else {
        freq[n] ++
    }
})
let uniq = Object.keys(freq)
console.log(typeof uniq[0])

>Solution :

You can use a Map instead, which can have keys of any type – but it’s slightly verbose too.

const freq = new Map();;
const nums = [1, 2, 3]
for (const num of nums) {
  freq.set(
    (freq.get(num) || 0) + 1
  );
}
const firstKey = [...freq.keys()][0];
console.log(typeof firstKey);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading