0

Im working on breaking down an algorithm called Top K Frequent Elements below i have the link to the problem and the solution. I cant understand what the 4th line is doing specifically on the right side of the = sign, could someone explain to me what it is that im assigning to the map[elements], it seems to perhaps be short hand for some type of if conditional because of the || statement but that is my best guess. If im missing any information or if my question is not clear please let me know and I will update the question as soon as I can https://leetcode.com/problems/top-k-frequent-elements/description/

var topKFrequent = (nums, k) => {
let map = {}
for(let element of nums){
    map[element] = (map[element] || 0) + 1
}
return Object.entries(map).sort((a,b) => b[1] -a[1]).map(val=>Number(val[0])).slice(0,k);
}
poopmachine
  • 53
  • 1
  • 6
  • 1
    `map[element] || 0` is just `map[element]`, or, if thats is falsy (as in `null`, `undefined`,`0`, `false`, `''`) it will be `0`. So basically this is just `0` as default if `map[element]` is not a number I assume. Then it is incremented by 1. – Lux Feb 03 '23 at 04:03
  • If `map[element]` has not been initialized, it will be `undefined` and therefore "falsy". The `||` operator will then evaluate the other side, which is 0. So it says "give me either `map[element]` or, if it's unset, 0". – Pointy Feb 03 '23 at 04:03

1 Answers1

0

We're examining this (map[element] || 0) + 1

  • map[element] looks up a specific value in the array
  • || 0 effectively returns a default value of 0 if the lookup above fails
  • + 1 adds one to the value from above

There is a newer and slightly cleaner way to handle this with the nullish coalescing operator ??. It accomplishes the same "default value" approach but removes some of the gotchas that may happen with the or operator ||.

NetByMatt
  • 703
  • 4
  • 13