EN
TypeScript - replace element in array
0 points
In TypeScript it is not intuitive at first time how to replace element in array. Replace operation can be achieved with Array.prototype.splice
method. This article is focused on how to do it.
xxxxxxxxxx
1
// ONLINE-RUNNER:browser;
2
3
// index: 0 1 2 3
4
const array: string[] = ['a', 'b', 'c', 'd'];
5
6
// removing element on 1st index position
7
// and inserting 'replaced item' element on same position
8
array.splice(1, 1, 'replaced item');
9
10
console.log(array);
Output (with NodeJS):
xxxxxxxxxx
1
[ 'a', 'replaced item', 'c', 'd' ]
Notes about
Array.prototype.splice
method:
- takes as first argument index of replaced element
- takes as second argument number of removed elements - in this case we remove one element and put on its place new one
- takes as third argument added element in removed element place