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.