When programming in JavaScript, sometimes we want to manipulate items within an Array. In this article, we show how to remove or add elements in an array using native JavaScript methods.
Add or remove items at the beginning or end of the array is simple. The functions pop () push (), shift () and unshift () can be used for this.
The first two functions manipulate final items in the array while shift () and unshift () manipulate the initial elements. Below is an example.
var arr = [1, 2, 3, 4, 5]; console.log ( "Original Array .." + arr); arr.pop (); console.log ( "After pop () ...." + arr); arr.push (8); console.log ( "After push () ..." + arr); arr.shift (); console.log ( "After shift () .." + arr); arr.unshift (7); console.log ( "After unshift ()" + arr);
The above code will result in the following sequence:
Original Array .. 1, 2, 3, 4, 5 After pop () .. 1, 2, 3, 4 After push () .. 1, 2, 3, 4, 8 After shift () ..: 2, 3, 4, 8 After unshift () ..: 7, 2, 3, 4, 8
Working with items that are in the middle of an array is not so easy, but we have the splice () function. Its syntax is simple and requires the following parameters: the original array, the initial position, the amount of items that will be affected, and if we are adding items, their value.
(Array) arr_original.splice (index, quantity, elem1, ..., elemX);
The examples below show how to remove two items from the array, from the second element and the addition of a new element in the 4th position.
arr= [1, 2, 3, 4, 5]; arr.splice (2, 2); // [1, 2, 5] arr= [1, 2, 3, 4, 5]; arr.splice (3, 0, 6); // [1, 2, 3, 6, 4, 5]
Important: the function makes changes directly in the original array and returns an array of items that have been affected – added or removed.
Do you know other ways to do this operation in JavaScript? Share your comments in the section below!
If you want to explore other questions, you can check our videos about JavaScript. Below are some examples:
You can also subscribe to some channels that broadcast in JavaScript, such as the following:
Another cool way to find out interesting things about JavaScript is to access our project page!
In 2024 we're witnessing a critical point in democratic technology: the integration of blockchain and…
We’re thrilled to announce an exciting opportunity for you to win not one but two…
Acquiring practical skills is crucial for career advancement and personal growth. Education Ecosystem stands out…
Artificial Intelligence (AI) has been making significant strides in various industries, and the software development…
Another week to bring you the top yield platforms for three of the most prominent…
If you hold a large volume of LEDU tokens above 1 million units and wish…
View Comments
Thanks for this clear and simple explanation. Solved my overall issue. Keep it up livecoding