DEV Community

Cover image for Array Methods
GiandoDev
GiandoDev

Posted on

Array Methods

With array often we need to find the position of an item (index).
For the primitive values we use IndexOf() method.
Alt Text
For function, array and object we use findIndex() .We will also se this later.
If we want to add an item in the beginning of an array we do this:
Alt Text
If we want to add more than one item we do this:
Alt Text
We add the other items separated by comma.
Sometimes we have to remove the first item of an array , we can do this in this way:
Alt Text
If we want remove more than one item in the beginning we do this:
Alt Text
In the code above we use shift() method two times to delete two items.
Now we talk about to add element and remove element in the end of an array.
If we want to add an item in the end of an array we can do this:
Alt Text
Now more than one item:
Alt Text
To delete the last item of an array we may do this:
Alt Text
More than one:
Alt Text
There is many occasions when we want to create a copy of our array to avoid changes in the original, we may perform this with slice() method.
Alt Text
In the end I want to talk about splice() that allow us to add, remove item / items from the beginning, the end or in the middle of an array. Is a penknife method.
Anatomy of splice() method:
Alt Text
Add one or more items in the beginnig of an array:
Alt Text
More than one:
Alt Text
Remove one from the beginning:
Alt Text
Remove more than one:
Alt Text
Add one item in the end:
Alt Text
Add more than one item in the end:
Alt Text
The last thing that I want to show you is how to add or remove Items from the middle of an array with the splice() method:
Add:
Alt Text
Remove:
Alt Text
And replace:
Alt Text

Discussion (0)