Skip to content
Advertisement

Javascript – Replace multiple elements in an array using index

Consider following array in Javascript:

var array1 = ['S', 'T', 'A', 'C', 'K', 'O', 'V', 'E', 'R', 'F', 'L', 'O', 'W'];

Now I want to replace all the elements at once from index 3 to 9 in following way:

array1 = ['S', 'T', 'A', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'L', 'O', 'W'];

Is it possible to achieve in javascript ?

Note: I want to perform following operation using array only

Advertisement

Answer

Use Array.fill()

var array1 = ['S', 'T', 'A', 'C', 'K', 'O', 'V', 'E', 'R', 'F', 'L', 'O', 'W'];

array1.fill('X', 3, 10)

console.log(array1)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement