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.
JavaScript – Manipulating elements at the beginning or end of an Array
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.
1 2 3 4 5 6 7 8 9 10 |
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:
1 2 3 4 5 |
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 |
JavaScript – Manipulating intermediate items from an Array
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.
1 |
(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.
1 2 3 4 5 6 7 |
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!