Hey There π
Welcome to Episode 2 of my Array Methods Explain Show.
as always, if you are here then i suppose you must have pre knowledge of javascript and arrays.
we will be discussing only one method in this episode
which is : SPLICE
This is the best method in javascript arrays armoury, as it can be used to insert, replace or delete an element from an array.
the syntax of splice method is :
- start :
The starting index from which you want to modify the array.
If start > length of array, then start will be set to length of array.
If start = -1, then start will be set to last element
- deleteCount (optional) :
The count of elements you want to remove starting from start, if its value is equal or larger than array.length then all elements are removed.
If its value is 0, then no element is removed, but then providing item1 parameter becomes compulsory.
- item1, item2, item3, .... itemN :
The elements to add, beginning from start.
If not provided then only elements are deleted.
It returns an element of deleted array elements, if no element is deleted then empty array is returned.
Now, Let's have a look at some of the examples to have better understanding
- To remove n elements from ith index. letβs take start as 1 and n as 1
let colors = ["Red", "Blue", "Yellow", "White", "Black"];
colors.splice(1,1); // from index : 1, delete 1 item
console.log(colors); // ["Red", "Yellow", "White", "Black"]
- Now, lets delete 2 elements and replace them βpinkβ and βpurpleβ
let colors = ["Red", "Blue", "Yellow", "White", "Black"];
colors.splice(2, 2, "Pink", "Purple"); // from index : 2, delete 2 item, add two items
console.log(colors); // ["Red", "Blue", "Pink", "Purple", "Black"]
- Now, lets just add one element βgreyβ without deleting any element
let colors = ["Red", "Blue", "Yellow", "White", "Black"];
colors.splice(1, 0, "Grey"); // from index 1, delete 0 item, add 1 item
console.log(colors); // ["Red", "Grey", "Blue", "Yellow", "White", "Black"]
- Last, splice returns the array of deleted elements
let colors = ["Red", "Blue", "Yellow", "White", "Black"];
let value = colors.splice(3, 1); // from index 3, delete 1 item
console.log(value); // ["White"]
console.log(colors); // ["Red", "Blue", "Yellow", "Black"]
Top comments (0)