Function appendToGroup

  • Appends a value to the dict entry associated with the specified key. If the key is not present in the dict, add it as an array containing value. The object is mutated for performance reasons, and the mutated dict is returned.

    Type Parameters

    • V

      Shape of dict object to update.

    • K extends DictKey = string

      Type of key that the specified dict object. This is useful if you have an object with a key that's an enum type.

    Parameters

    • dict: Record<K, V[]>

      Object with a key and array value.

    • key: K

      Key of the object for which to append value.

    • value: V

      Value that gets appended to the array in the object.

    Returns Record<K, V[]>

    The mutated object with the specified key/value appended to the specified dict.

    const food = {
    fruits: ["banana", "apple", "orange"],
    vegs: ["lettuce"],
    };

    // For existing groups:
    appendToGroup(food, "vegs", "cucumber");

    console.log(food.vegs);
    // ["lettuce", "cucumber"]

    // For new group:
    appendToGroup(food, "candy", "Snickers");

    // Note that the group was created:
    console.log(food.candy);
    // ["Snickers"]
  • Appends a value to the array value associated with the array index. If the index is not present in the groupedArray, add it and append the value to the array. The object is mutated for performance reasons, and the mutated groupedArray is returned.

    Type Parameters

    • V

      Type of values in the specified groupedArray.

    • K = number

      Key of the values in the specified array (i.e. number).

    Parameters

    • groupedArray: V[][]

      Array of arrays (with specified index as the key).

    • index: K

      Index of the array to update group values.

    • value: V

      Value that gets appended to the array in the dictionary.

    Returns V[][]

    The mutated array with the specified index/value appended to the specified groupedArray.

    const food = [
    ["banana", "apple", "orange"],
    ["lettuce"],
    ];

    // For existing groups:
    appendToGroup(food, 1, "cucumber");

    console.log(food[1]);
    // ["lettuce", "cucumber"]

    // For new group:
    appendToGroup(food, 2, "Snickers");

    // Note that the group was created:
    console.log(food[2]);
    // ["Snickers"]