Concat two arrays on different indexes in javascript

Viewed 1285

I have two arrays:

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

arr2 = ['2', '5']

I want to replace the 'x' in the first array, with the numbers in the second array in the exact order so I would obtain something like this:

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

I have no idea where to start. I've tried with concat() and slice() but with no result.

5 Answers

Iterate arr1 with Array.map(), and use an outer counter. Whenever the value is 'x', use to counter to get the value from arr2, and 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 can mutate arr2, you can use shift to get the item instead of 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);

You could map array 1 and check the value and take value at an index for the other array by using a clsure of the index.

var array1 = ['1', 'x', '0', 'x'],
    array2 = ['2', '5'],
    result = array1.map((i => v => v === 'x' ? array2[i++] : v)(0));
    
console.log(result);

You can do something like this

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

var arr2 = ['2', '5'];

for(var i = 0; i < arr1.length; i++) {
  if (arr1[i] == "x") {
    arr1[i] = arr2[0];// replace 
    arr2.shift(); // delete first element
  }
}

console.log(arr1);

If both arrays are always in correct order, this is trivial:

var arr3 = arr1.map(item => item === 'x' ? arr2.shift() : item);

It better using forloop than map because its faster if you have a bigger arrays

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++;
}



}

Related