Skip to main content

Command Palette

Search for a command to run...

How to Keep Track of Counts in an Array

Updated
2 min read
How to Keep Track of Counts in an Array
Y
Crafting delightful applications with #React #ReactNative #NextJS #TypeScript #GraphQL

Here is the instruction for the coding exercise:

Create a function that takes in an array of numbers and returns an object in the specified format based on their counts.

Input array: [1, 2, 3, 3, 4, 3, 2, 4, 4, 5, 4]

Expected return: 
{
  unique: [1, 5],
  twice: [2],
  threePlus: [3, 4]
}

Notice the keys in the return object are set. So a type should be created for it. What are the other questions you could ask?

  1. Should there be an empty array in the return object if there is no value in that category, or not have the category in the object at all?

  2. Are the numbers sorted?

Below is a solution to set an empty array by default and keep the order of the numbers in the original list:

const numbers = [1, 2, 3, 3, 4, 3, 2, 4, 4, 5, 4];

type CountType = 'unique' | 'twice' | 'threePlus';

let counts: Record<CountType, number[]> = {
  unique: [],
  twice: [],
  threePlus: []
};
let countMap: Record<number, number> = {};

const checkCount = (numbers: number[]): Record<CountType, number[]> => {

  for (let n of numbers) {
    countMap[n] = countMap[n] ? countMap[n]+1 : 1
  }
  for (let c in countMap){
    if(countMap[c] === 1){
      counts.unique.push(Number(c)); //when you set a number as the key, js converts it into string
    } else if (countMap[c] === 2){
      counts.twice.push(Number(c));
    } else {
      counts.threePlus.push(Number(c));
    }
  }
  return counts;
}

If the numbers in the returned object should be sorted, the list should be sorted at the beginning instead of looping through the values in the return object again. And you won’t need the map to keep track of the count because you can compare the previous number with the next and get the count of that number.

More from this blog

UI Dev

18 posts

Rao Ventures Tech Blog