remove

Removes elements from an array at a specified index.

1. Code

/**
 * Removes element(s) from an array based on the given index(es).
 *
 * @template T - The type of elements in the array.
 * @param {T[]} array - The array from which elements will be removed.
 * @param {number | number[]} index - The index(es) of the element(s) to be removed.
 * @returns {T[]} - A new array with the specified element(s) removed.
 */
const remove = <T>(array: T[], index: number | number[]): T[] => {
  const len = array.length;
  if (Array.isArray(index)) {
    // convert negative indices to their positive counterparts
    const indices = index.map((i) => (i < 0 ? len + i : i));
    return array.filter((_, i) => !indices.includes(i));
  }
  index = index < 0 ? len + index : index;
  return array.filter((_, i) => i !== index);
};

export default remove;

2. Installation

npx @jrtilak/lazykit@latest add remove -ts

3. Description

The remove function is a generic function in TypeScript that is designed to remove elements from an array at a specified index. The function takes two parameters: an array arr of type T[], an index or array of indices of type number.

It returns a new array with the elements removed at the specified index without modifying the original array. If the index is negative, the index is treated as an index from the end of the array.

4. Props

Prop

Type

Default Value

array*array---
index(s)*number | number[]---

5. Examples

import remove from ".";

// for a index
remove([1, 2, 3, 4, 5], 2);
// Expected Output: [1, 2, 4, 5]

// for array of indices
remove([1, 2, 3, 4, 5], [1, 3]);
// Expected Output: [1, 3, 5]

// for negative index
remove([1, 2, 3, 4, 5], -2);
// Expected Output: [1, 2, 3, 5]

// for mixed indices
remove([1, 2, 3, 4, 5], [1, -3]);
// Expected Output: [1, 4, 5]