Erase elements from an array in JavaScript
This post will discuss how to erase elements from an array in JavaScript.
There are several ways to erase elements from an array in JavaScript, depending on which elements we want to remove and how we want to modify the original array. Here are some of the most common functions:
1. Using pop() function
To erase the last element of an array, we can use the pop() function, which removes and returns the last element of the array. The function modifies the original array by reducing its length by one. Here’s an example:
|
1 2 3 4 5 6 |
let arr = [1, 2, 3, 4]; let last = arr.pop(); console.log(arr); // [1, 2, 3] console.log(last); // 4 |
2. Using shift() function
To erase only the first element of an array, we can use the shift() function, which removes and returns the first element of the array. It also changes the length of the array and shifts the remaining elements to lower indexes. Here’s an example:
|
1 2 3 4 5 6 |
let arr = [1, 2, 3, 4]; let first = arr.shift(); console.log(arr); // [2, 3, 4] console.log(first); // 1 |
3. Using splice() function
To erase one or more elements from any position of an array, we can use the splice() function, which takes two or more arguments: the start index, the number of elements to delete, and optionally any elements to insert at that position. The function returns an array of the deleted elements and modifies the original array. Here’s an example:
|
1 2 3 4 5 6 |
let arr = [1, 2, 3, 4]; let middle = arr.splice(1, 2); console.log(arr); // [1, 4] console.log(middle); // [2, 3] |
4. Using filter() function
To erase elements from an array based on a condition, we can use the filter() function, which takes a callback function that returns true or false for each element. The function returns a new array with only the elements that pass the test and does not modify the original array. Here’s an example:
|
1 2 3 4 5 6 |
let arr = [1, 2, 3, 4]; let even = arr.filter(x => x % 2 === 0); console.log(arr); // [1, 2, 3, 4] console.log(even); // [2, 4] |
That’s all about erasing elements from an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)