JavaScript: Add an element to the precise middle of an array

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?

Answer №1

To divide the array, consider inserting the item at half of its length.

function insertIntoMiddle(array, item) {
    array.splice(array.length >> 1, 0, item);
    return array
}

console.log(...insertIntoMiddle([1, 3], 2));
console.log(...insertIntoMiddle([1, 3, 7, 9], 5));

Answer №2

To find the middle of an array, you can use a method called two pointers. The first pointer moves with a step of +2 and the second pointer moves with a step of +1 until the end of the array.

When the first pointer reaches the end of the array, the second pointer will be positioned at the middle.

At this point, you can insert an item at the position of the second pointer in the array.

function insertIntoMiddle(array, item) {
  let i = 0;
  let j = 0;
  while (array[i]) {
    i += 2;
    j++;
  }
  array.splice(j, 0, item);
  return array;
}

console.log(insertIntoMiddle([1, 3, 7, 9], 5));
console.log(insertIntoMiddle([1, 3], 2));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize flexbox to create a list that is displayed in a column-reverse layout

I am facing a challenge in displaying the latest chat person in the 1st position (active) using Firebase. Unfortunately, Firebase does not have a date field which makes it difficult to achieve this. I have attempted converting the date into milliseconds an ...

"Implementing a select value in React.js using option values and mapping through iterations, with the

Currently, I am working on a React application where I encountered an issue with the map method during iteration. I have a select box that needs to be filled with numbers ranging from 0 to a specified value. My expected output should be [{label:0,value:0 ...

What is the best way to loop through a list of questions and save the answers in an array of user input?

I'm encountering a challenge with iterating through an array of questions to correctly display them on the document. The initial code snippet provided below demonstrates what I aim to accomplish without using prompts. Currently, I have set up an arr ...

You cannot use Arrays.setAll with boolean data types

I am attempting to create a large array and experiment with lambda expressions, but for some reason the following code snippet is not working as expected: cells = new boolean[this.collums][this.rows]; IntStream.range(0, cells.length).forEach(x -> Array ...

Optimal method for file uploading with Node.js

How can I effectively manage file uploads in node js? I would like users to be able to upload profile images with the following specifications: -Validated size of at least 200 * 200 -Accepted file formats are png, jpg, jpeg, or gif -Additional functi ...

Managing components within an array

I have this array called match where match[0] = [2014-05-30 15:21:20,781] DEBUG [scheduler-4] (DiamondSchedulerRunner.java:41) Current node is not a manager of:publishEmail in tenant:0 [2014-05-30 15:21:20,781] DEBUG [scheduler-1] (DiamondSchedulerRunne ...

Tap and conceal feature on a mobile website

I seem to be facing a JavaScript challenge. On the desktop version of my website, I've managed to create a functionality where hovering over a button reveals some text, and clicking anywhere else on the site hides the text. However, I'm now stru ...

Automated task scheduled to execute every minute between the hours of 8am and 4.30pm using Cloudwatch Events

I am facing an issue with my working CRON schedule. It currently runs from 8am to 5pm and I need to change it to end at 4:30pm. Is it possible to set a specific half-hour time interval in CRON? Below is the current setting for my CRON: 0/1 8-17 ? * MON- ...

Tips on safeguarding your templates while working with SailsJS and AngularJS

I am currently working on a web application using SailsJS and AngularJS. My project requires session management to track user login status. I came across this helpful tutorial and implemented an index.ejs view located in the /view folder. Within the index. ...

Selecting an option containing text using Selenium and Xpath

During one of my tests, I am attempting to choose an option that includes the word "Current." The dropdown menu appears as follows: <select name="lead" class="wide"> <option value="">-- Select a lead --</option ...

Creating multiple divs with input fields dynamically using JavaScript is a useful skill to have

I need to generate 3 input text boxes for gathering user input on names and email addresses. These inputs must be created dynamically, meaning that as the user clicks on the email input field, a new line with all three elements should be generated. Below i ...

Guide to obtaining ngPrime autocomplete text when the button is clicked within Angular 6

I am currently utilizing the ngPrime autocomplete feature to retrieve data from a service. My goal is to capture the text entered in the autocomplete field whenever a button is clicked. I attempted to access the value using getElementById.value within th ...

Having difficulty in choosing and displaying the dropdown values

Below is the code snippet: WebElement pooldropdown=driver.findElement(By.xpath("/html/body/section/section[2]/div[1]/select")); Select sel = new Select(pooldropdown); List<WebElement> list = sel.getOptions(); System. ...

The item is not functioning properly as intended

After delving into the concepts of prototype and proto, I believed that I had grasped the concept. However, something doesn't seem to add up. Can someone shed light on why directly accessing an Object like this does not yield the desired outcome? fun ...

I am having trouble with using document.getElementById().value to retrieve text input. Can anyone help me understand why it's not

It's puzzling to me why document.getelementbyid().value isn't working as expected. Upon inspecting the console, no input seems to be sent or printed out in the console. function callApi() { var keyword = document.getElementById('user_ ...

Creating a continuous loop in JQuery when clicking on a table row

I seem to be encountering an issue with what appears to be an infinite loop. My problem arises while trying to create a table dynamically using Ajax. Each row of the table contains a button alongside a thumbnail image and some text. I wish for the button ...

Prevent Android WebView from attempting to fetch or capture resources such as CSS when using loadData() method

Context To many, this situation might appear to be repetitive. However, I assure you that it is not. My objective is to import html data into a WebView, while being able to intercept user hyperlink requests. During this process, I came across this helpfu ...

Leverage the Nuxeo client SDK with Angular 6 for seamless integration with RESTClient in

Looking to integrate the Nuxeo ClientSdk with my Angular 6 client to consume its REST API, but facing issues due to the lack of typescript definitions for this JavaScript package. Tried importing the library into my project using the following code snippe ...

Enhance the "content switcher" code

I have been working on improving my "contenthandler" function. It currently changes different articles when I click different buttons, which I am satisfied with. However, I believe there may be a better approach to this and would appreciate any advice on h ...

What is the reason for not receiving a JSON object in the response from my personal node.js/express server?

-- Exploring a New Challenge -- I am currently working on creating an e-form signup for a client as part of our business marketing strategy service. The form design is complete and looks excellent. Now, I need to connect it to the existing API that our bu ...