remove

Removes elements from an array at a specified index.

1.
/**
2.
* Removes elements from an array at a specified index.
3.
**/
4.
const remove = <T,>(array: T[], index: number | number[]): T[] => {
5.
const len = array.length;
6.
if (Array.isArray(index)) {
7.
// convert negative indices to their positive counterparts
8.
const indices = index.map((i) => (i < 0 ? len + i : i));
9.
return array.filter((_, i) => !indices.includes(i));
10.
}
11.
index = index < 0 ? len + index : index;
12.
return array.filter((_, i) => i !== index);
13.
};
14.
15.
export default remove;

1. Installtion

npx @jrtilak/lazykit add remove

2. Parameters

  • array (T[])
    The array from which elements will be removed.

  • index (number | number[])
    The index or indices of the elements to be removed. This can be a single index or an array of indices. Negative indices are supported and will remove elements from the end of the array.

3. Returns

  • T[]
    Returns a new array with the specified elements removed. The original array remains unchanged.

4. Type Parameters

  • T
    The type of elements in the array. This allows the function to work with arrays of any type, ensuring type safety for the elements being removed.

5. Example Usage

1. Remove a single element by index

1.
import remove from '@/helpers/remove';
2.
3.
const numbers = [10, 20, 30, 40, 50];
4.
const result1 = remove(numbers, 2);
5.
6.
console.log(result1);
7.
// Output: [10, 20, 40, 50]

2. Remove multiple elements by indices

1.
import remove from '@/helpers/remove';
2.
3.
const numbers = [10, 20, 30, 40, 50];
4.
const result2 = remove(numbers, [1, 3]);
5.
6.
console.log(result2);
7.
// Output: [10, 30, 50]

3. Using negative indices

1.
import remove from '@/helpers/remove';
2.
3.
const numbers = [10, 20, 30, 40, 50];
4.
const result3 = remove(numbers, [-1, -3]);
5.
6.
console.log(result3);
7.
// Output: [10, 20, 40]