Home > Mobile >  Javascript hash on a set of numbers
Javascript hash on a set of numbers

Time:11-28

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

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

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related