introduction
This article is going to talk about how to add, Update and Delete a element or elements from Array.
Examples
Following array will be used for example.
interface User {
name: string
age: number
}
const arr: User[] = [
{
name: 'John',
age: 20,
},
{
name: 'Arthur',
age: 32,
}
]
Add
Push
The push()
method in Array adds an element at the end of an array.
arr.push({
name: 'Emily',
age: 18,
})
The element will be at index 2 (Length of array is 3).
Unshift
The unshift()
method adds an element at the beginning of an array.
arr.unshift({
name: 'Emily',
age: 18,
})
The element will be at index 0
Add at a specific index #1
The splice()
method in Array helps to add an element at specific index.
const index = 1
arr.splice(inedx, 0, {
name: 'Emily',
age: 18,
})
Add at a specific index #2
Although the splice()
method is very simple to use, it change the original array.
const newArr = [
...arr.slice(0, index),
{
name: 'Emily',
age: 18,
},
...arr.slice(index)
]
The slice()
method returns a new copied array from first start to end (end can be excluded).
It means that this way doesn't change original array.
Update
Bracket []
arr[0] = {
name: 'Emily',
age: 18,
}
The bracket [index]
will change element at number between two brackets.
It's well-know way, but it's not good idea if you don't want to change original array.
map()
The map()
method in Array creates a new array populated with the results of calling a provided function on every element in the calling array.
arr = arr.map(el => {
if (el.name === 'John') {
return {
...el,
age: 25,
}
}
return el
})
It will change all matched condition in if
. In the example, all elements which has John as name will be changed.
splice()
It is also possible that the splice()
method replace element at index.
arr.splice(inedx, 0, {
name: 'Emily',
age: 18,
})
Delete
the pop()
method in Array deletes last element from an array. It also returns deleted element.
The pop()
method is opposite to the push()
method.
Delete last element pop()
arr.pop()
The pop()
method returns deleted element.
Delete first element shift()
the pop()
method in Array deletes first element from an array. It also returns deleted element like the pop()
method.
The pop()
method is opposite to the unshift()
method.
arr.shift()
The shift()
method returns deleted element.
Delete element at specific index
The splice()
method can be used for removing element at specific index.
const index = 1
arr.splice(index, 1)
Delete many elements filter()
The filter()
method in Array returns a new copied array. It's useful to delete multiple elements depending on your preference.
arr = arr.filter(el => el.age !== 20)
The filter()
method will not change original array, so you have to reassign data.