In Javascript, I can add an element at a specific index in an array by inserting elements from a different

I am faced with a coding problem involving two separate Javascript arrays:

['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
['a', 'b', 'c']

The task at hand is to incorporate elements from the second array into specific positions within the first array, specifically every 4th or nth index instance, resulting in:

['a', '1', '2', '3', '4', 'b', '5', '6', '7', '8', 'c', '9', '10', '11', '12']

This parameter n must be adjustable, allowing for the placement of elements at different locations in the array as needed.

If you have any solutions, especially those utilizing ES6 functionality, please share them. Thank you for your help!

Answer №1

To cycle through the smaller array, use the forEach method and implement splice() for element insertion.

let arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
let arr2 = ['a', 'b', 'c']

function addElements(arr1,arr2,n){
  arr1 = arr1.slice();
  arr2.forEach((element,index) => {
    arr1.splice(index*n+index,0,element);
  })
  return arr1;
}

console.log(addElements(arr1,arr2,4))

Answer №2

Give this a shot

For each item in array b, insert it into array a at intervals based on the length of b.
    

Answer №3

Implement a forEach loop with an iterator as shown below:

let arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
let arr2 = ['a', 'b', 'c'];

let index = 0;
arr2.forEach(function(v){
  arr1.splice(index, 0, v);
  index += 5;
});

console.log(arr1);

Now in terms of ES6, here is the updated approach:

let arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
let arr2 = ['a', 'b', 'c'];

let index = 0;
Array.from(arr2).forEach((v)=> {
  arr1.splice(index, 0, v);
  index += 5;
});

console.log(arr1);

Answer №4

Utilize the method Array.flatMap() to iterate through the second array, then extract the corresponding sequence from the first array using Array.slice(), and finally merge it with the current element utilizing spread operator. Employ Array.concat() combined with slice to append any remaining items if present.

const combineArrays = (size, additionalArr, primaryArr) => 
  additionalArr.flatMap((element, index) => [element, ...primaryArr.slice(size * index, size * (index + 1))])
  .concat(primaryArr.slice(size * additionalArr.length))

const mainArray = ['apple', 'banana', 'cherry', 'date', 'fig', 'grape', 'honeydew', 'kiwi', 'lemon', 'mango', 'nectarine', 'orange']
const secondaryArray = ['ant', 'bat', 'cat']

console.log(JSON.stringify(combineArrays(3, secondaryArray, mainArray)))
console.log(JSON.stringify(combineArrays(4, secondaryArray, mainArray)))
console.log(JSON.stringify(combineArrays(5, secondaryArray, mainArray))

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

Is there a way to transfer the chosen maximum and minimum price values to a JavaScript function within a select tag in HTML?

I have a search form that includes select options with two values. However, I want to have two select options for both the Max and Min price values. <input type="hidden" id="budget_min" name="filter_budget_min" value="0" /> <select onchange="upda ...

When the component mounts in React using firestore and Redux, the onClick event is triggered instantly

I am facing an issue with my component that displays projects. Each project has a delete button, but for some reason, all delete buttons are being automatically triggered. I am using Redux and Firestore in my application. This behavior might be related to ...

What could be causing my Svelte store's subscribe() method to trigger despite no change in value?

One of the Svelte stores I am using is called activeAccountIndexStore: export const activeAccountIndexStore: Writable<number | "native" | null> = writable(null); Initially, the value of the store is null, but it gets set to either a spec ...

Parsing a multidimensional JSON array in Java: A step-by-step guide

I have a JSON array object with two dimensions as shown below {"enrollment_data":{"status":"Active","notes":"None","id":"983761"}} To extract the status, notes, and id from the above JSON array object, I have written the following code: JSONParser parse ...

Uncovering the Mystery: The Issue of Duplicate Items When Writing Arrays to localStorage in JavaScript

Struggling to create a Javascript quiz for my coding bootcamp. I'm facing challenges with retrieving and saving previous high scores from local storage. Can someone explain why the newScore is being written TWICE to the highScores arrayItems array in ...

Looking to customize session data for my online game within the same interface

I have successfully coded a game called Ninja Gold using PHP with CodeIgniter. The game works by setting session variables (Gold and Activities) when the index page loads if they are not set already. Each location clicked adds a certain amount of gold to t ...

What is the best way to display HTML code using Vue syntax that is retrieved from an Axios GET request

I am currently working on a project that involves a Symfony 5 and Vue 3 application. In this setup, a Symfony controller creates a form and provides its HTML through a JSON response. The code snippet below shows how the form HTML is returned as a string: i ...

How can I make the arrows work on a secondary slider with EasySlider1.7?

I finally managed to get 2 sliders working on my page after reading through several other tutorials. However, I am facing an issue with the Prev & Next arrows on the second slider as they don't seem to work properly. I inherited this page from someon ...

Changing array values in React using the setState method and index

Is the code below acceptable for updating an array value using an index? updateArrayValue = index => e => { const { spaceship } = this.state // ['SpaceX', 'NASA', 'Blue Origin'] spaceship[index] = e.target.value t ...

Exploring the controller logic in Sails.js index.ejs

I'm struggling to understand how to integrate dynamic logic into the homepage of my Sails.js application. Currently, the homepage is static, but I want to display data on the index.ejs page. I have a MainController with an index function that retrieve ...

Store the results in the database following the execution of a protractor test

I am completely new to angular protractor testing. I have created some test cases using the protractor framework with jasmine runner BDD style. Within a single test class, I have 10 to 12 specs, each with an expectation. Currently, I am running these tests ...

Determine your age by manually inputting your date of birth

Utilizing Ajax Calendar, I have successfully implemented a feature to calculate age based on the date selected in one textbox and display it in another. However, I am facing two challenges. First Issue:- I want the Age Textbox to be disabled so users cann ...

Filtering Typeahead results based on multiple fields in Angular

My typeahead feature currently filters based on a person's name only. However, my person object contains additional fields such as surname, and I would like the filter to work based on both name and surname. Here is the existing typeahead code using ...

Is it possible to iterate through an object with multiple parameters in Op.op sequelize?

Currently, I am in the process of setting up a search API that will be able to query for specific parameters such as id, type, originCity, destinationCity, departureDate, reason, accommodation, approvalStatus, and potentially more in the future. const opt ...

React app experiencing inconsistent loading of Google Translate script

In my React application, I have integrated the Google Translate script to enable translation functionality. However, I am facing an issue where the translator dropdown does not consistently appear on every page visit. While it sometimes loads properly, oth ...

Exploring an array using bluebird promises

I am currently facing an issue where I need to iterate over an array containing promises. My goal is to multiply all the values in the array by 2 and then return the updated array: var Bluebird = Promise.noConflict(); var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9 ...

The ajax Success function fails to work when set to receive JSON data

My task involves adding an attendance record for a group of students within a classroom using a Bootstrap modal. Below is the code snippet for my Bootstrap modal, containing a form: <div id = "add_attendance_modal" class = "modal fade&qu ...

Error encountered with the OpenAI API: "The module 'openai' does not have a defined export for 'Configuration'"

I'm encountering an issue while attempting to make an API call to the GPT-3.5 API from OpenAI; all imports from OpenAI are resulting in a 'has no exported member' error. import { Configuration, OpenAIApi } from "openai"; import { a ...

Obtain the jQuery dialog's closure event within the $.Ajax completion function

I have developed a custom jQuery plugin that utilizes jQuery Dialog to showcase messages. Specifically, I am using it within my jQuery $.ajax -->done function. My goal is to capture the close event of the Dialog in the .ajax function so that I can redir ...

Displaying JSON information in an HTML table with JavaScript

I successfully displayed JSON data in an HTML table. Here is the snippet I used: $("#example-table").tabulator({ height:"300px", fitColumns:true, tooltips:true, columns:[ {title:"Month", field:"Month", sorter:"string"}, {title:"Numbers", ...