Combining arrays at different indexes using JavaScript

Given two arrays:

arr1 = ['1', 'x', '0', 'x']

arr2 = ['2', '5']

The task is to replace the 'x' values in the first array with the numbers from the second array in the same order, resulting in:

arr3 = ['1', '2', '0', '5']

I am unsure how to approach this problem. I have attempted using concat() and slice() methods without success.

Answer №1

Loop through arr1 using Array.map(), and maintain an external counter. Whenever the element is 'x', utilize the counter to access the value from arr2, then increment the counter:

const arr1 = ['1', 'x', '0', 'x']

const arr2 = ['2', '5']

let counter = 0;
const result = arr1.map(c => c === 'x' ? arr2[counter++] : c);

console.log(result);

If you have the flexibility to modify arr2, you can employ shift to retrieve the item instead of utilizing the counter:

const arr1 = ['1', 'x', '0', 'x']

const arr2 = ['2', '5']

const result = arr1.map(c => c === 'x' ? arr2.shift() : c);

console.log(result);

Answer №2

In order to retrieve values from both arrays based on a mapping of array 1, you can use a closure to iterate through the indexes and select the correct values.

var arr1 = ['a', 'b', 'c', 'd'],
    arr2 = ['1', '2', '3'],
    result = arr1.map((index => value => value === 'b' ? arr2[index++] : value)(0));
    
console.log(result);

Answer №3

Here is an example of how you can achieve this:

const array1 = ['apple', 'banana', 'orange', 'kiwi'];
const array2 = ['pear', 'grape'];

for(let i = 0; i < array1.length; i++) {
  if (array1[i] === "orange") {
    array1[i] = array2[0];// replace 
    array2.shift(); // delete first element
  }
}

console.log(array1);

Answer №4

When both arrays are consistently in the correct order, handling this is a simple task:

let newArray = firstArray.map(element => element === 'x' ? secondArray.shift() : element);

Answer №5

It is more efficient to use a for loop instead of map when working with larger arrays.

For example:

var arr1 = ['1', 'x', '0', 'x'];
    
var arr2 = ['2', '5'];

var counter = 0;
for(int i = 0; i < arr1.length; i++){

if(arr1[i] === 'x'){
  arr1[i] = arr2[counter];
  counter++;
}

}

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

Using Yii framework in PHP to showcase a widget within a Tab interface

After using Yii framework for a while now, I have found the widgets to be extremely helpful in simplifying development. Specifically, Yii bootstrap has been my go-to for extensions. However, I am struggling to fully grasp how each widget functions. My mai ...

Activating JavaScript Function only when Needed Leads to Unusual Outcomes

I've created a dropdownlist with the following declaration: <select onchange="reloadValues(this,event);"> ... options here </select> When the user changes the selection, reloadValues is called and everything works perfectly. Now, I wan ...

Display a progress bar that shows completion based on the maximum value supplied

I successfully created a progress bar using HTML, CSS, and Javascript. It functions perfectly up to a provided value of 100. However, if a value higher than 100 is given, the progress completes but the value continues to change until it reaches the maximum ...

``req.body is not being properly populated when data is sent using form-data, causing

When I send data in my Node.js application as raw JSON/x-www-form-urlencoded from Postman, it gets passed successfully. However, when sending the data as form-data from either Postman or my Angular frontend, the req.body is coming back as undefined. I have ...

What is the best way to add portfolio projects into a React application?

I am currently building a portfolio using react. I am having trouble navigating to my projects through localhost:3000. The projects are stored in my includes folder and are not created with react, so it is different from using XAMPP as my server. My file ...

Is it possible to divide the outcome of an array in an ejs file across multiple pages?

Currently, I am in the process of constructing a blog using nodejs, express, and mongodb. Upon creating an article, it gets stored in a database alongside all other articles. For the website's homepage, I implemented an array with objects to locally s ...

Error: Unexpected character 'o' encountered in AngularJS syntax

Whenever I try to call this controller, it gives me an error. hiren.controller('hirenz' , function($scope , $http , $location , $routeParams){ $http.post((rootURL + "music") , {'alpha' : $routeParams.alpha , 'name' : $rou ...

How can I design a versatile button in HTML/CSS3/jQuery/Javascript that utilizes images for borders and corners for maximum scalability?

Is there a way to create a completely scalable button in HTML/CSS3/jQuery+Plugins using images for borders and corners? I have attempted a messy method, but I am confident that there are more effective solutions available. The approach I considered invol ...

Creating copies and assigning individual identities to movieclips

I need help with an issue I'm facing with arrays and the snap function in ActionScript3. I'm working on a cube game where players need to drag cubes of different colors together and have them snap to the right of each other. All cubes are Movie ...

Python's alternative code to MATLAB's vec2mat

Currently, I am in the process of converting a piece of MATLAB code to Python. The code is not very pythonic at the moment, but I plan on refining it later. In the original MATLAB script, there is a function called vec2mat from the Communications systems ...

Arranging elements in ascending order in Java

I've been attempting to arrange an array in ascending order, following the instructions in example 104.5. Despite carefully reviewing my code multiple times, I'm unable to identify the mistake. Below is the code snippet from my sorting class: imp ...

What is the best method for toggling between three different elements in an array?

I have been working on a language switcher feature in my Next.js project. The idea is to have three languages available, with the ability for the user to click on a language and have it become the active one, while moving the previously active language t ...

Problems with Ajax functionality

Excuse my rusty JavaScript skills but I'm attempting to use an AJAX call to a PHP file, pass it a plan type, and then determine if there are enough available slots for the plan. If so, return true; otherwise, false. Below is the Form in XHTML: <fo ...

Having difficulty retrieving objects within a foreach loop of object keys that do not meet the criteria of the string.prototype.replace method

Currently, I am working on looping over objects within a key:value array in JavaScript to use the string.prototype.replace method for paths to JS files in GulpJS concat tasks. The objective is to generate a list of paths that GULP can utilize, but they re ...

Unable to Close Modal with Selectize in Rails 6

During my journey to update an old Go Rails video tutorial for selectize functionality to work with Rails 6, I encountered a challenge. I have established a relationship where each item belongs to a series. class Item < ApplicationRecord belongs_to :s ...

Is there a record log for the werewolf in the book "Articulate Coding: The Lycanthrope's

I've been tackling the challenges of Eloquent JavaScript at the Lycanthrope's Log, but I'm struggling to grasp a particular code snippet. Despite my efforts in checking values and testing with console.log, this piece of code still eludes me: ...

Is there a way to identify and eliminate duplicate objects within an array of objects?

Is there a way to identify and remove duplicate objects with id: 3 while retaining only the id: 3 in the children of id: 2? Consider this example array object: const data = [ { "id": 1, "name": ABC, "parentID": ...

Steps for adding an onclick function to a collection of div elements

My current project involves utilizing the Flickr API and I am interested in creating a popup div that opens when clicking on each image. The goal is to display the image in a larger form, similar to how it's done using Fancybox. I'm looking for ...

What sets apart map and collect in Ruby?

I have searched online and found conflicting opinions - is there a distinction between using map and collect on an array in Ruby/Rails? Although the documentation does not indicate any differences, could there be variations in functionality or efficiency? ...

What is the best method for ensuring that my JavaScript tracking script has been properly installed on the customer's website?

We provide a SAAS analytics application that functions similarly to Hotjar and Google Analytics. To track user data, our customers must integrate our JavaScript code into their websites. How can we confirm if the script has been successfully integrated in ...