utilitish - v0.0.10
    Preparing search index...

    Interface Array<T>

    interface Array<T> {
        first(): undefined | T;
        last(): undefined | T;
        sum(this: number[]): number;
        sum(this: T[], selector: Selector<T, number>): number;
        unique(): T[];
        chunk(size: number): T[][];
        average(this: number[]): number;
        average(this: T[], selector: Selector<T, number>): number;
        groupBy<K>(this: T[], selector: Selector<T, K>): Map<K, T[]>;
        compact(): T[];
        enumerate(): [T, number][];
        sortAsc(this: (string | number)[]): T[];
        sortAsc(this: T[], selector: Selector<T, string | number>): T[];
        sortDesc(this: (string | number)[]): T[];
        sortDesc(this: T[], selector: Selector<T, string | number>): T[];
        swap(i: number, j: number): this;
        shuffle(): T[];
        toMap<K, V>(this: [K, V][]): Map<K, V>;
        toMap<K, V>(
            this: T[],
            keySelector?: Selector<T, K>,
            valueSelector?: Selector<T, V>,
        ): Map<number | K, T | V>;
        toObject<K extends PropertyKey, V>(this: [K, V][]): Record<K, V>;
        toObject<K extends PropertyKey, V>(
            this: T[],
            keySelector?: Selector<T, K>,
            valueSelector?: Selector<T, V>,
        ): Record<K | number, V | T>;
        toSet<K>(this: T[], selector?: Selector<T, K>): Set<T | K>;
        countBy<K>(this: T[], selector?: Selector<T, K>): Map<T | K, number>;
        [n: number]: T;
    }

    Type Parameters

    • T

    Hierarchy

    • RelativeIndexable<T>
      • Array

    Indexable

    • [n: number]: T
    Index

    Methods

    • Returns the first element of the array, or undefined if the array is empty.

      Returns undefined | T

      The first element or undefined if the array is empty

      [1, 2, 3].first(); // 1
      [].first(); // undefined
    • Returns the last element of the array, or undefined if the array is empty.

      Returns undefined | T

      The last element or undefined if the array is empty

      [1, 2, 3].last(); // 3
      [].last(); // undefined
    • Calculates the sum of the array values. Supports bare number arrays or objects with a selector to extract numeric values.

      Parameters

      • this: number[]

      Returns number

      The sum of all values (0 for empty arrays)

      If array is not of type number[] and no selector is provided

      [1, 2, 3].sum(); // 6
      [].sum(); // 0
      [{ x: 1 }, { x: 2 }].sum(x => x.x); // 3
      [{ x: 1 }, { x: 2 }].sum('x'); // 3
      • For number arrays, no selector is required
      • For object arrays, use property key string or callback function
      • Returns 0 for empty arrays regardless of type
    • Parameters

      Returns number

    • Returns a new array with only unique elements based on strict equality (===). Preserves order of first occurrence.

      Returns T[]

      A new array with duplicate values removed

      [1, 1, 2, 2, 3].unique(); // [1, 2, 3]
      [{id: 1}, {id: 1}, {id: 2}].unique(); // [{id: 1}, {id: 1}, {id: 2}] (objects compared by reference)
      • Uses Set internally for efficiency
      • Only removes duplicates based on strict equality
      • For object arrays, same reference is considered equal
    • Splits the array into chunks (sub-arrays) of a specified maximum size.

      Parameters

      • size: number

        Maximum size of each chunk (must be positive integer)

      Returns T[][]

      A new array of chunks, where each chunk has at most size elements

      If size is not a positive integer

      [1, 2, 3, 4].chunk(2); // [[1, 2], [3, 4]]
      [1, 2, 3].chunk(2); // [[1, 2], [3]]
      [1, 2, 3, 4, 5].chunk(2); // [[1, 2], [3, 4], [5]]
      • Last chunk may have fewer elements if array length is not divisible by size
      • Empty array returns an empty array
    • Calculates the average (mean) of the array values. Supports bare number arrays or objects with a selector to extract numeric values.

      Parameters

      • this: number[]

      Returns number

      The average of all values (0 for empty arrays)

      If array is not of type number[] and no selector is provided

      [2, 4, 6].average(); // 4
      [].average(); // 0
      [{x: 2}, {x: 4}].average(x => x.x); // 3
      [{x: 2}, {x: 4}].average('x'); // 3
      • For number arrays, no selector is required
      • Returns 0 for empty arrays (prevents division by zero)
      • For object arrays, use property key string or callback function
    • Parameters

      Returns number

    • Groups array elements into a Map based on a key returned by the selector. Elements with the same key are grouped together in an array.

      Type Parameters

      • K

        The type of grouping key (extracted from selector)

      Parameters

      • this: T[]
      • selector: Selector<T, K>

        Function or property key to extract the grouping key

      Returns Map<K, T[]>

      A Map where keys map to arrays of grouped items

      const arr = [{type: 'a', v: 1}, {type: 'b', v: 2}, {type: 'a', v: 3}];
      arr.groupBy('type');
      // Map { 'a' => [{type: 'a', v: 1}, {type: 'a', v: 3}], 'b' => [{type: 'b', v: 2}] }

      arr.groupBy(x => x.v % 2);
      // Map { 1 => [{type: 'a', v: 1}, {type: 'a', v: 3}], 0 => [{type: 'b', v: 2}] }
      • Order of groups in Map matches insertion order (first occurrence of key)
      • Empty array returns an empty Map
    • Removes all falsy values from the array. Removes: false, null, 0, "" (empty string), undefined, NaN.

      Returns T[]

      A new array with all falsy values removed

      [0, 1, false, 2, '', 3, null, undefined, NaN].compact();
      // [1, 2, 3]
      • Uses JavaScript's falsy value definition
      • Returns a new array (original is not modified)
    • Enumerates the array into tuples of [value, index]. Similar to Python's enumerate but returns value first.

      Returns [T, number][]

      An array of [value, index] tuples

      ['a', 'b', 'c'].enumerate();
      // [['a', 0], ['b', 1], ['c', 2]]
      • Value comes first (before index), unlike JavaScript's map callback
      • Index is always the enumeration index (0-based)
    • Returns a new sorted copy of the array in ascending order. Creates a new array without modifying the original.

      Parameters

      • this: (string | number)[]

      Returns T[]

      A new array sorted in ascending order

      If elements are not sortable or selector returns invalid type

      [3, 1, 2].sortAsc(); // [1, 2, 3]
      ['c', 'a', 'b'].sortAsc(); // ['a', 'b', 'c']
      [{v: 2}, {v: 1}].sortAsc(x => x.v); // [{v: 1}, {v: 2}]
      [{v: 2}, {v: 1}].sortAsc('v'); // [{v: 1}, {v: 2}]
      • For primitive arrays, no selector needed (must be number or string)
      • Selectors must return number or string for comparison
      • Returns new array; does not mutate original
      • Empty arrays return empty array
    • Parameters

      • this: T[]
      • selector: Selector<T, string | number>

      Returns T[]

    • Returns a new sorted copy of the array in descending order. Creates a new array without modifying the original.

      Parameters

      • this: (string | number)[]

      Returns T[]

      A new array sorted in descending order

      If elements are not sortable or selector returns invalid type

      [1, 3, 2].sortDesc(); // [3, 2, 1]
      ['a', 'c', 'b'].sortDesc(); // ['c', 'b', 'a']
      [{v: 1}, {v: 2}].sortDesc(x => x.v); // [{v: 2}, {v: 1}]
      [{v: 1}, {v: 2}].sortDesc('v'); // [{v: 2}, {v: 1}]
      • For primitive arrays, no selector needed (must be number or string)
      • Selectors must return number or string for comparison
      • Returns new array; does not mutate original
      • Empty arrays return empty array
    • Parameters

      • this: T[]
      • selector: Selector<T, string | number>

      Returns T[]

    • Swaps the elements at two indices within the array. Modifies the array in place and returns the array itself (for chaining).

      Parameters

      • i: number

        First index to swap

      • j: number

        Second index to swap

      Returns this

      The modified array (same reference as this)

      If indices are not integers

      If any index is out of bounds (negative or >= length)

      const arr = [1, 2, 3];
      arr.swap(0, 2); // arr is now [3, 2, 1]
      arr === arr.swap(0, 2); // true (returns same array)
      • Does nothing if i === j
      • Modifies original array (not immutable)
      • Validates both indices are valid integers
    • Returns a new array with elements shuffled randomly. Uses Fisher-Yates algorithm for uniform distribution. Does not modify the original array.

      Returns T[]

      A new shuffled array

      const arr = [1, 2, 3, 4, 5];
      const shuffled = arr.shuffle();
      // shuffled might be [3, 1, 5, 2, 4] (order is random)
      arr; // [1, 2, 3, 4, 5] (unchanged)
      • Returns new array instance (original unchanged)
      • Uses Math.random() so results vary
      • Empty arrays return empty array
      • Fisher-Yates algorithm ensures unbiased distribution
    • Converts an array to a Map using keys and optionally values extracted from elements. Supports multiple input formats: pairs array, property key, or selector functions.

      Type Parameters

      • K

        The type of Map keys

      • V

        The type of Map values

      Parameters

      • this: [K, V][]

      Returns Map<K, V>

      A Map with extracted key-value pairs

      // From pairs
      [['a', 1], ['b', 2]].toMap(); // Map { 'a' => 1, 'b' => 2 }

      // Using property key
      [{id: 1, name: 'foo'}, {id: 2, name: 'bar'}].toMap('id');
      // Map { 1 => {id: 1, name: 'foo'}, 2 => {id: 2, name: 'bar'} }

      // Using selectors
      [{id: 1, name: 'foo'}].toMap(x => x.id, x => x.name);
      // Map { 1 => 'foo' }

      // Default (uses index)
      ['a', 'b'].toMap();
      // Map { 0 => 'a', 1 => 'b' }
      • For pairs array, no parameters needed
      • For objects, provide key as string or selector function
      • Value defaults to the entire element if not specified
      • Index is used as key if no keySelector provided
    • Type Parameters

      • K
      • V

      Parameters

      Returns Map<number | K, T | V>

    • Converts an array to a plain JavaScript object using keys and optionally values extracted from elements. Leverages Map.prototype.toObject() internally for consistency and validation.

      Type Parameters

      • K extends PropertyKey

        Type of object keys (must be PropertyKey: string | number)

      • V

        Type of object values

      Parameters

      • this: [K, V][]

      Returns Record<K, V>

      A plain object with array elements as properties

      If any key is null, undefined, or not a valid PropertyKey (string/number)

      // From pairs
      [['a', 1], ['b', 2]].toObject(); // { a: 1, b: 2 }

      // Using property key
      [{id: 1, name: 'foo'}, {id: 2, name: 'bar'}].toObject('id');
      // { 1: {id: 1, name: 'foo'}, 2: {id: 2, name: 'bar'} }

      // Using selectors
      [{id: 1, name: 'foo'}].toObject(x => x.id, x => x.name);
      // { 1: 'foo' }

      // Default (uses index)
      ['a', 'b'].toObject();
      // { 0: 'a', 1: 'b' }
      • For pairs array, no parameters needed
      • For objects, provide key as string or selector function
      • Value defaults to the entire element if not specified
      • Index is used as key if no keySelector provided
      • Validates keys are valid PropertyKeys (not null/undefined)
      • Symbols are not supported in plain objects
    • Type Parameters

      • K extends PropertyKey
      • V

      Parameters

      Returns Record<K | number, V | T>

    • Returns a Set containing the unique elements of the array. Optionally applies a selector function or property key to extract values for the Set.

      Type Parameters

      • K

        The type of selected values for the Set

      Parameters

      • this: T[]
      • Optionalselector: Selector<T, K>

        Optional property key or function to select values

      Returns Set<T | K>

      A Set of unique elements or selected values

      [1, 2, 2, 3].toSet(); // Set { 1, 2, 3 }

      [{id: 1}, {id: 2}, {id: 1}].toSet(x => x.id);
      // Set { 1, 2 }

      [{id: 1}, {id: 2}].toSet('id');
      // Set { 1, 2 }
      • Without selector, stores the entire element in the Set
      • With selector, stores the extracted value instead
      • Uses Set's built-in uniqueness (based on === equality)
      • Empty array returns empty Set
    • Groups array elements by a key and counts the occurrences of each key. Returns a Map where keys map to their occurrence counts.

      Type Parameters

      • K

        The type of grouping key

      Parameters

      • this: T[]
      • Optionalselector: Selector<T, K>

        Optional property key or function to extract grouping key

      Returns Map<T | K, number>

      A Map where keys map to their occurrence counts

      ['a', 'b', 'a', 'c', 'b', 'a'].countBy();
      // Map { 'a' => 3, 'b' => 2, 'c' => 1 }

      [{type: 'x'}, {type: 'y'}, {type: 'x'}].countBy(x => x.type);
      // Map { 'x' => 2, 'y' => 1 }

      [{type: 'x'}, {type: 'y'}].countBy('type');
      // Map { 'x' => 1, 'y' => 1 }
      • Without selector, counts entire elements
      • With selector, counts extracted keys
      • Uses === equality for counting
      • Empty array returns empty Map