-2

I need to find and replace each element in the array with an index that corresponds to the numbers from another array

arrayA = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
arrayB = [2, 5, 6]
valueToReplace = 'X'
expectedResult = ['a', 'X', 'c', 'd', 'X', 'X', 'g']

Thanks in advance

Abd Elbeltaji
  • 473
  • 2
  • 13
Boris
  • 31
  • 4

3 Answers3

4
var var arrayA = ['a','b','c','d','e','f','g'],
arrayB = [2,5,6],
valueToReplace = 'X';
for(let i of arrayB) {
     arrayA[i] = valueToReplace
}
console.log(arrayA);
JS_INF
  • 467
  • 3
  • 10
2

One answer has been accepted but I want to add: If you don't want to overwrite arrayA you can use this code, cloning array (check this question also) and iterating over arrayB as suggested by @pilchard:

let arrayA = ['a','b','c','d','e','f','g']
const arrayB = [2,5,6]
const valueToReplace = 'X';

let expectedResult = [...arrayA];
arrayB.forEach(value => expectedResult[value-1] = valueToReplace)
console.log(expectedResult)

Also, to get the same output as you expect I've used value-1 because index starts at 0, so value 2 is third position and has to be second position.

So giving positions [2,5,6] and expecting result [a,X,c,d,X,X,g] is neccessary to use value - 1.

array:    [a,X,c,d,X,X,g]
index:     0,1,2,3,4,5,6
value:         2     5,6
value-1:     1     4,5

Note how using value it will update positions 3, 6 and 7 instead of 2, 5 and 6.

J.F.
  • 13,927
  • 9
  • 27
  • 65
  • 1
    It would be more efficient to first clone `arrayA` and then iterate `arrayB` as the accepted answer does, no need for a nested loop. – pilchard Aug 12 '21 at 21:41
1

you can use array.map to change the array values in each iteration:

let arrayA = ['a', 'b', 'c', 'd', 'e' ,'f', 'g']
let arrayB = [2, 5, 6]
let valueToReplace = 'X';
let result = arrayA.map((el, i)=> arrayB.includes(i + 1) ? valueToReplace : el );
console.log(result); 
Abilogos
  • 4,777
  • 2
  • 19
  • 39
Abd Elbeltaji
  • 473
  • 2
  • 13