I'm looking for a concise way to build a hash table from an array (of numbers) in JavaScript.
(This comes up a lot, at least on a lot of those O(n^2)-type problems that could be optimized to run in one-pass, like those Leetcode-type 'algorithm' problems.)
It seems like it could be a concise one-liner... But here's a two-liner of what I have:
const freq = {}; // An Object is often used to implement a Hash Table in JavaScript
nums.forEach(num => freq[num] = freq[num] === undefined ? 1 : freq[num] + 1);
... Assuming nums
is an Array<number>
and freq represents a conceptual hash table data structure, like so:
const nums = [2, 0, 2, 0, 0, 3, 0, 2, 0, 1];
// freq == { '0': 5, '1': 1, '2': 3, '3': 1 }
Does anybody know of a more syntactically concise way to achieve this?