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
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
Share Improve this question asked Oct 31, 2021 at 5:42 Nikunj VNikunj V 2931 gold badge5 silver badges21 bronze badges 3-
2
array1.forEach((a,b,c)=>array1[b]=(b<9 && b>2)?'X':a);
– dandavis Commented Oct 31, 2021 at 5:47 - @dandavis your boundaries are off, 9 is inclusive – Samathingamajig Commented Oct 31, 2021 at 5:50
- touchè. it's late here, but the main point is closure-ing the object to be mutated (array1) in the iteration callback – dandavis Commented Oct 31, 2021 at 5:51
4 Answers
Reset to default 10Use 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)
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);
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);
It sure does.
const arr = ['a', 'b', 'c', 'd', 'e']
function replaceWithX(start, end) {
for (let i = start; i <= end; i++) {
arr[i] = 'x'
}
}
replaceWithX(1, 3)
console.log(arr) // ["a", "x", "x", "x", "e"]