find the mode of all elements in an array in typescript

To find the mode of all elements in an array in TypeScript, one approach is to use a counting algorithm. Here's the code to implement this algorithm:

index.ts
function findMode(arr: number[]): number[] {
  const modeMap = new Map<number, number>();
  let maxCount = 0;
  let modes: number[] = [];

  arr.forEach((num) => {
    let count = modeMap.get(num) || 0;
    modeMap.set(num, count + 1);
    if (count + 1 > maxCount) {
      maxCount = count + 1;
      modes = [num];
    } else if (count + 1 === maxCount) {
      modes.push(num);
    }
  });

  return modes;
}
412 chars
19 lines

The findMode function takes an array of numbers and returns an array of the most frequent elements in the input array. The implementation uses a map to keep track of the counts of each number in the input array. It then iterates over the keys of the map to find the keys with the largest values (i.e., the most frequently occurring numbers). If there is a tie, both numbers are added to the output array.

gistlibby LogSnag