Fill a JavaScript array with values inserted in the middle position

I'm having trouble populating an array:

var arr2 = ["x", "y", "z"];

I want to insert a random number/value between each original value using a for loop, like this:

for (let i = 1; i < arr2.length; i+2) {
   arr2.splice(i, 0, Math.random());
}

But my browser freezes because the length of arr2 changes with every splice, creating an infinite loop. I tried another approach:

var len = arr2.length;

for(let j = 1; j < len; j+2) {
   arr2.splice(j, 0, Math.random());
}

Now things are not working as expected. I suspect that len is changing again.

I need to increment j by two because after the first splice, arr2 looks like this:

["x", Math.random(), "y", "z"];

However, since j = 3 and the condition is j < len, the only explanation is that len is being modified once more.

Any insights would be appreciated. Ultimately, I want the array to end up like this:

arr2 = ["x", Math.random(), "y", Math.random(), "z"];

Answer №1

for (var x = 1; x < list2.length; x+2) {

The variable x is not properly incrementing in this line. Please update it to:

for (var x = 1; x < list2.length; x+=2) {

Using += will ensure that x increases by 2 each time.

Answer №2

Here is a suggestion you might want to consider:

let letters = ["a", "b", "c"];

let length = letters.length;

// Iterate through all elements except the last one with step of 1
for(let index = 0; index < (length - 1); ++index) {
   // Insert undefined starting from index 1 and moving 2 steps for each element
   letters.splice(1 + (index * 2), 0, undefined);
}

Answer №3

Here's a simple way to achieve the desired result:

let myArray = ["x", "y", "z"],
    lengthOfArray = myArray.length,
    finalOutput = [];

for ( let j = 0; j < lengthOfArray; j++ ) {
  finalOutput.push(myArray[j]);
  if ( j < lengthOfArray - 1 ) {
    finalOutput.push(null);
  }
}

// final output:
// ["x", null, "y", null, "z"]

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

Attempting to develop a worldwide npm package. Upon running my script, I encounter the message "The designated path cannot be found."

I have been working on converting my npm module into a global command. You can find the code at this link. However, when I try to run $ seed, an error stating "The system cannot find the path specified" is displayed, indicating that it recognizes it as a ...

Angular: How to Disable Checkbox

Within my table, there is a column that consists solely of checkboxes as values. Using a for loop, I have populated all values into the table. What I have accomplished so far is that when a checkbox is enabled, a message saying "hey" appears. However, if m ...

Is it possible to edit YouTube images or embed YouTube iframes without needing an account?

Recently, I developed a YouTube video sharing system but have encountered some uncertainties. My approach involves extracting the YouTube ID and embedding it in an iframe (I wonder if YouTube permits this). To enhance the visual appeal of the posts, especi ...

How can serial numbers be sorted using a JavaScript If Statement based on 2 criteria?

I'm currently enrolled in a JavaScript coding course where I am tackling a task involving validating serial numbers. The requirement is to check if a serial number is valid and then add it to an array to store all the valid serial numbers. The criteri ...

Variations in ajax requests coupled with a polling mechanism

Suppose the initial ajax call is made right away, and the function called by the controller keeps looping until it reads something, as shown below: def FirstAjax(): while True: if something is read: val = something brea ...

Error message: The variable "data" is not defined in next.js

Being new to React, I recently used getStaticprops to retrieve data from an API for a filter gallery project. However, I encountered an issue when trying to access the {props: data} outside of the blog function - it resulted in a Reference Error stating th ...

The ajax response is returning the entire page's html code instead of just the text content from the editor

I've been working with CKEditor and I'm using AJAX to send the editor's content via POST method. However, when I try to display the response in a div, the HTML for the entire page is being returned instead of just the editor's content. ...

Leveraging the jQuery live() function to optimize heavy usage of Ajax on a website

Trying to ensure that all scripts are properly executed as content is loaded and removed from the page using jQuery load has been a challenge. The most effective approach so far has been the live function, but I have encountered difficulties in getting it ...

What is the best way to cause an error to occur upon launching an ExpressJS server?

Below is a brief code snippet I've provided: ... const url = typeof process.env.url === 'string' ? process.env.url : {do not start a server} ... server.start(options, ({ port }) => console.log(`Server is running on http://localhost:${po ...

Executing Javascript dynamically in VueJS: Learn how to run code from a string efficiently

Currently, I am developing a website with VueJS that enables selected users to upload scripts for automatic execution upon page load. For instance, here is an example of the type of script a user may input: <script src="https://cdnjs.cloudflare.com/aja ...

Creating artwork: How to resize images without losing clarity

Struggling to display an image in a canvas element that needs to be a certain percentage of its parent container's width. Despite my efforts, the image seems to blur once added to the canvas, which is not the desired effect. I attempted to disable th ...

Adjusting the size of <nav> element to accommodate its child elements

I've exhausted all possible CSS solutions today in an attempt to make my parent nav tag home-main-nav-menu resize based on its children and grandchildren, but it just won't cooperate. If anyone could provide a clear explanation on how to solve th ...

"Learn how to add up elements in an array based on their unique IDs and generate a new array using

There is an array called data that looks like this: const data = [ {"id": "One", "number": 100}, {"id": "One", "number": 150}, {"id": "One", "number": 200}, ...

Creating a table with a static first column and vertical text positioned to the left of the fixed column

To create a table with the first column fixed, refer to this fiddle link: http://jsfiddle.net/Yw679/6/. You also need a vertical text to be positioned to the left of the fixed column in a way that it remains fixed like the first column. The disparities be ...

A tool developed in Javascript that allows for the conversion of .ini files to .json files directly on the client

Does anyone know of a JavaScript library that can convert .ini files to .json files on the client-side? I checked out this library, but it doesn't meet my requirements. Here is an example of an .ini file: [Master_Settings:1] Model Name=RC-74DL IP Ad ...

How to set and update the value of a TextField in ReactJS using useState and implement an onchange event handler for the input field in TypeScript

Just starting out with ReactJS and MUI development, I have a form with a MuiText field in TypeScript. Seeking assistance on how to use the useState method to update the text field value. Additionally, looking for guidance on adding an onchange function to ...

Arrange divs on the screen in a specific formation

I am exploring ways to position specific divs in the middle of the screen to create a pearl necklace-like shape. The desired shape is as follows: 0 0 0 0 0 0 0 0 0 0 My aim is to achieve this using jQuery on a mobile ...

Encountered an issue while trying to install npm package express-generator globally

Encountering an error when trying to run npm install express? Looking for the correct solution? Read on. -bash-3.2$ npm install express-generator -g npm WARN engine <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a2bfb7b5a2 ...

Is there a way to direct the user's cursor to a specific location on the page when they hover over an image?

I'm interested in creating a script that can manipulate the user's mouse position when they hover over an image. For example, if I hover over the image, I want the mouse to be dragged lower towards a specific text. Is there a method to achieve th ...

Should the Express.js router be required directly or stored in a variable before use?

I've been pondering a performance question related to express.js. In my server.js file, I have all the routes defined and the child routes are imported as follows: const ROUTE__FOO = require('./routes/foo') const ROUTE__BAR = require(' ...