insert

Inserts elements into an array at a specified index.

1.
/**
2.
* Inserts elements into an array at a specified index.
3.
**/
4.
const insert = <T,>(
5.
arr: T[],
6.
index: number,
7.
[...items]: T[],
8.
recursive: boolean = false,
9.
): T[] => {
10.
const isNegativeIndex = index < 0;
11.
12.
if (isNegativeIndex) {
13.
throw new Error('Negative index is not supported!');
14.
}
15.
16.
if (!recursive) {
17.
const newArr = [...arr.slice(0, index), ...items, ...arr.slice(index)];
18.
return newArr;
19.
} else {
20.
const shouldInsert = Math.floor(arr.length / index);
21.
let newArr = [...arr];
22.
for (let i = 0; i < shouldInsert; i++) {
23.
const insertIndex = (i + 1) * index + i * items.length;
24.
newArr = [
25.
...newArr.slice(0, insertIndex),
26.
...items,
27.
...newArr.slice(insertIndex),
28.
];
29.
}
30.
return newArr;
31.
}
32.
};
33.
34.
export default insert;

1. Installtion

npx @jrtilak/lazykit add insert

2. Parameters

  • arr (T[])
    The original array into which elements will be inserted.

  • index (number)
    The index at which to insert the specified elements. Negative indices are not supported and will throw an error.

  • items (...T[])
    The elements to be inserted into the array at the specified index.

  • recursive (optional) (boolean)
    A flag that determines whether to insert the items multiple times based on the calculated condition. Defaults to false.

3. Returns

  • T[]
    Returns a new array with the specified elements inserted at the given index. If recursive is true, the items are inserted multiple times based on the array length and index.

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 inserted elements.

5. Usage

1. Basic Insertion

1.
import insert from '@/helpers/insert';
2.
3.
const array = [1, 2, 3, 4, 5];
4.
const result = insert(array, 2, [10, 20]);
5.
6.
console.log(result);
7.
// Output: [1, 2, 10, 20, 3, 4, 5]

2. Insertion with Negative Index

1.
import insert from '@/helpers/insert';
2.
3.
const array = [1, 2, 3, 4, 5];
4.
const result = insert(array, -1, [99]);
5.
6.
console.log(result);
7.
// Output: Error

3. Recursive Insertion with strict Option

1.
import insert from '@/helpers/insert';
2.
3.
const array = [1, 2, 3, 4, 5];
4.
const result = insert(array, 2, [7, 8], true);
5.
6.
console.log(result);
7.
// Output: [1, 2, 7, 8, 3, 4, 7, 8, 5]