📊 Calculates the mode value(s) of a list.

Info

Mode: The most frequent number—that is, the number that occurs the highest number of times.

Info

If all elements in the array are unique (occur only once), the function returns an empty array [].

Syntax

TypeScript
import { mode } from '@opentf/std';

mode<T>(
  arr: T[] = [],
  cb?: (val: T, index: number) => string | number
): (string | number)[]

Parameters

  • arr: The source array.

  • cb: An optional iteratee invoked for each element to generate the value to be used for mode calculation.

Returns

An array containing the most frequent element(s). Returns [] if all elements are unique or if the input array is empty.

Sparse array holes are ignored.

Examples

TypeScript
mode([1]) //=> []

mode([1, 2, 3, 4, 5]) //=> []

mode([4, 2]) //=> []

mode([4, 2, 3, 2, 2]) //=> [2]

mode([0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 4]) //=> [1, 2]

mode(['a', 'b', 'b', 'c', 'c']) //=> ['b', 'c']

mode([{ n: 1 }, { n: 2 }, { n: 3 }, { n: 2 }], ({ n }) => n) //=> [2]
Last updated on
Edit this page