Javascript Array Methods
Arrays in Javascript provide a lot of methods, To make things easier.
Add Items
There are many ways to add items in an array Like:
- push
- unshift
We use push method to add items to the end of an array.
let arr = [1,2,3,4];
arr.push(5);
console.log(arr); // [1,2,3,4,5]
And, The second method is unshift is used for add items to the beginning.
let arr = [2,3,4];
arr.unshift(1);
console.log(arr); // [1,2,3,4]
How to delete an element from the array?
For delete any element form an array the is a arr.splice()
method.
Let's know the syntax of splice()
method:
let arr = [1,2,3];
arr.splice(startIndex, num_of_items, ...addItems);
Now if we have an array like this:
let names = ['Ahmed', 'Mohamed', 'Mahmoud', 'islam'];
And, we need to delete any items. Easily we use splice()
method like this:
names.splice(0,1); // here we say please start from index 0 and delete one item.
console.log(names); // ['Mohamed', 'Mahmoud' , 'islam']
let removed = names.splice(1, 1);
console.log(removed); // ['Mahmoud']
we can add items after with delete items.
let arr = ['hello', 'world'];
names.splice(0,1, ...arr);
console.log(names); // ['hello', 'world', 'Mohamed', 'Mahmoud', 'islam']
If you need to read the other parts of this article follow us:
Facebook Page :
Semantic Code
Hashnode :
Semantic Code
dev.to :
Ahmed Ibrahim
Top comments (0)