This is not bad at all. A few things can be simplified a bit.
Instead of iterating this way:
for(var i = 0; i < arr.length; i++){
You can do it like this:
for (var i in arr) {
The i
loop variable will take on exactly the same values as your original loop,
but this writing style is shorter, and more natural.
When checking if arr[i]
exists in numMapping
:
if(numMapping[arr[i]] === undefined){
A simpler and more natural way is this:
if (!(arr[i] in numMapping)) {
As a tiny optimization, instead of this:
if (!(arr[i] in numMapping)) { numMapping[arr[i]] = 0; } numMapping[arr[i]] += 1;
This is somewhat better:
if (!(arr[i] in numMapping)) {
numMapping[arr[i]] = 1;
} else {
numMapping[arr[i]] += 1;
}
Because this way you save one extra lookup of arr[...]
and also numMapping[...]
,
by directly assigning 1 instead of 0 and then incrementing later.
At a few places the indentation was off,
and I would recommend a bit more generous spaces in if(...){
and for(...){
statements, use if (...) {
and for (...) {
instead (like in my examples above).