Skip to main content

Command Palette

Search for a command to run...

Trying to understand code that locates a unique number.

Published
2 min readView as Markdown
K

I'm a software developer from UK, living in Hong Kong.

let counts = {};

  for(let i = 0; i < arr.length; i++) {
    if(counts[arr[i]] === undefined) {
      counts[arr[i]] = 1;
    } else {
      counts[arr[i]] += 1;
    }
  }

let counts = {};

This line creates an empty object named counts. In JavaScript, an object is a collection of properties, which are essentially key-value pairs. Here, we'll use the counts object to keep track of how many times each number appears in the array.

for(let i = 0; i < arr.length; i++) { ... }

This for loop goes through each element in the array arr. i is the index of the current element.

if(counts[arr[i]] === undefined) { ... }

This if statement checks whether the counts object has a property for the current number arr[i]. If it doesn't (which is the case when counts[arr[i]] is undefined), this means it's the first time we've seen this number.

counts[arr[i]] = 1;

If it's the first time we've seen the number, we set its count to 1 in the counts object. arr[i] is the current number and acts as the key in our counts object, and the value is the count of that number.

else { ... }

This else clause runs if the counts object already has a property for the current number arr[i] (in other words, if we've seen this number before).

counts[arr[i]] += 1;

If we've seen the number before, we increment its count by 1.

So, in conclusion, these lines of code go through each number in the array, count how many times each number appears, and store those counts in the counts object. After running this code, counts will look something like {1: 2, 2: 1, 3: 1} for an input array [1, 1, 2, 3], which means the number 1 appears 2 times, and numbers 2 and 3 appear 1 time each.

More from this blog

Kai's Blog

19 posts