Sorry if this is a repeat question, but I couldn't find the answer despite searching.
Let's say there's an array of unknown length and you want to insert items at a specific position, such as the center. How can you achieve this?
Here's an example function that inserts an item into the middle of an array:
function insertIntoMiddle(array, item) {
array.splice(4, 2, item);
return array.sort();
}
const items = insertIntoMiddle([1, 3], 2);
console.log(insertIntoMiddle([1, 3], 2), '<-- should be [1 , 2 , 3]');
console.log(insertIntoMiddle([1, 3, 7, 9], 5), '<-- should be [1, 3, 5, 7, 9]');
The output will look like this:
[1, 2, 3] <-- should be [1 , 2 , 3]
[1, 3, 5, 7, 9] <-- should be [1, 3, 5, 7, 9]
But what if the length of the array is unknown, like when reading data from a growing database? Is it possible to insert into the exact middle in such cases?