Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 847
Nikunj V Avatar asked Oct 31 '21 05:10

Nikunj V


People also ask

How do you replace an element in an array by index?

To replace an element in an array:Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.

How do I replace multiples in a string?

Replace Multiple Characters in a String using replaceAll # To replace multiple characters in a string, chain multiple calls to the replaceAll() method, e.g. str. replaceAll('. ', '!

How do I remove multiple elements from an array?

The idea is to use JavaScript filter() method to remove multiple items from an array. The following code example returns the new array of filtered values using the latest includes() method. Here's an alternative version which uses the indexOf() method instead of the includes() method.

Can we change array index?

Array indexing starts at zero in C; you cannot change that.


Video Answer


3 Answers

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)
like image 133
ProGu Avatar answered Nov 02 '22 06:11

ProGu


Use array splice() method

var array1= ['S', 'T', 'A', 'C', 'K', 'O', 'V', 'E', 'R', 'F', 'L', 'O', 'W'];
// At position 3, delete 7 and add 7 elements: 
array1.splice(3, 7, "X","X","X","X","X","X","X");

console.log(array1);
like image 26
Osama Avatar answered Nov 02 '22 07:11

Osama


One way is with Array.prototype.map:

This loops through every index of the array, and if the index is between 3 and 9 (inclusive), set it to 'X', otherwise keep it as the original chr (character)

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

var array2 = array1.map((chr, idx) => 3 <= idx && idx <= 9 ? 'X' : chr);

console.log(array2);
like image 35
Samathingamajig Avatar answered Nov 02 '22 07:11

Samathingamajig