Education
Software Development Executive - II
Last updated on Feb 1, 2024
Last updated on Jan 17, 2024
In web development, arrays are a vital part of JavaScript. An array is a special type of object that can store multiple values under a single name. The values in an array, referred to as elements, can be accessed using their index number, representing their position in the array.
1let array = ['Apple', 'Banana', 'Cherry']; 2console.log(array[0]); // Output: Apple 3
The importance of managing elements in arrays must be considered. In JavaScript, arrays are dynamic, meaning that you can add or remove elements from an array after creation. This flexibility allows developers to manipulate the existing elements in an array to suit the specific needs of their programs.
In JavaScript, an array is an ordered list of values enclosed in square brackets and separated by commas. Each value in the array is an element. JavaScript arrays can hold any value, including numbers, strings, and 'JavaScript objects'.
1let array = [1, 'Apple', {name: 'John Doe', age: 30}]; 2
The original array remains unchanged until you perform an operation that modifies it. For instance, you can add new elements to the array or remove elements from it. You're left with the remaining elements when you remove an element from an array. The array length property can determine the number of elements in an array.
1let array = ['Apple', 'Banana', 'Cherry']; 2console.log(array.length); // Output: 3 3
Removing elements from an array in JavaScript can be accomplished in several ways, each with its unique characteristics and use cases. Before we delve into these methods, it's important to understand some fundamental concepts: the Original Array and the New Array.
In JavaScript, when we talk about the original array, we're referring to the array as before any operations were performed. Any modification to this array, such as removing an element, can either mutate the original array or result in a new array, depending on the method used.
For instance, some methods like splice and pop mutate the original array. They remove elements directly from the array they are called upon.
1let originalArray = [1, 2, 3, 4, 5]; 2originalArray.pop(); // Removes last element 3console.log(originalArray); // Output: [1, 2, 3, 4] 4
On the other hand, methods like filter create a new array that meets certain conditions, leaving the original array unchanged.
1let originalArray = [1, 2, 3, 4, 5]; 2let newArray = originalArray.filter(num => num !== 5); // Creates a new array without 5 3console.log(originalArray); // Output: [1, 2, 3, 4, 5] 4console.log(newArray); // Output: [1, 2, 3, 4] 5
Several methods are available in JavaScript to remove elements from an array, each with unique characteristics and use cases. Let's explore some of the most commonly used methods.
The splice method is a versatile tool that removes, replaces, or inserts elements in a JavaScript array. It directly modifies the original array and returns a new array containing the removed elements.
The splice method takes two arguments: the start index and the number of elements to remove. It then removes the specified elements and automatically updates the array length.
1let array = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry']; 2let removedElements = array.splice(1, 2); // Removes 'Banana' and 'Cherry' 3console.log(array); // Output: ['Apple', 'Date', 'Elderberry'] 4console.log(array.length); // Output: 3 5
After the splice method is called, the original array is left with the remaining elements. If no elements are left, it becomes an empty array.
1let array = ['Apple', 'Banana', 'Cherry']; 2let removedElements = array.splice(0, 3); // Removes all elements 3console.log(array); // Output: [] 4
The delete operator in JavaScript can remove an element from an array. However, it works differently from the splice method. Instead of reducing the array length, it leaves a hole in the array, with the value of the removed element being 'undefined'.
When you use the delete operator, it removes the array element, but it doesn't change the array length. This can lead to unexpected results if not handled properly.
1let array = ['Apple', 'Banana', 'Cherry']; 2delete array[1]; // Removes 'Banana' 3console.log(array); // Output: ['Apple', <1 empty item>, 'Cherry'] 4console.log(array.length); // Output: 3 5
Even if you delete all elements in an array using the delete operator, it doesn't result in an empty array. Instead, you're left with an array of the same length, but all its elements are 'undefined'.
1let array = ['Apple', 'Banana', 'Cherry']; 2delete array[0]; 3delete array[1]; 4delete array[2]; 5console.log(array); // Output: [<3 empty items>] 6
In JavaScript, the filter method returns a new array containing all elements that pass a function-provided condition. It's a great way to remove unwanted elements from an array without affecting the original array.
The filter method doesn't change the original array. Instead, it creates a new array with the elements that pass the test. The original array remains unchanged.
1let array = [1, 2, 3, 4, 5]; 2let newArray = array.filter(num => num !== 3); // Removes 3 3console.log(array); // Output: [1, 2, 3, 4, 5] 4console.log(newArray); // Output: [1, 2, 4, 5] 5
The remaining elements in the new array are those that passed the test. The filter method returns an empty array if no elements pass the test.
1let array = [1, 2, 3, 4, 5]; 2let newArray = array.filter(num => num > 5); // No elements pass the test 3console.log(newArray); // Output: [] 4
The pop and shift methods in JavaScript are used to remove elements from the ends of an array. The pop method removes the last element, while the shift method removes the first array element. Both methods mutate the original array.
The pop method removes the last element from an array and returns that element. This method changes the length of the array.
1let array = ['Apple', 'Banana', 'Cherry']; 2let lastElement = array.pop(); // Removes 'Cherry' 3console.log(array); // Output: ['Apple', 'Banana'] 4console.log(lastElement); // Output: 'Cherry' 5
The shift method works similarly to the pop method, but instead of removing the last element, it removes the first element from an array. The shift method also returns the removed element and changes the array's length.
1let array = ['Apple', 'Banana', 'Cherry']; 2let firstElement = array.shift(); // Removes 'Apple' 3console.log(array); // Output: ['Banana', 'Cherry'] 4console.log(firstElement); // Output: 'Apple' 5
You can effectively manage and manipulate the first array element using the shift method. However, remember that, like the pop method, the shift also mutates the original array.
While methods like splice, delete, filter, pop, and shift are common ways to remove elements from a JavaScript array, other advanced techniques offer more flexibility and control. Let's explore some of these techniques.
Introduced in ES6, the rest operator (...) provides a new way to work with arrays and objects in JavaScript. When used in array destructuring, it can help create a new array by omitting specific elements.
The rest operator assigns the remaining elements to a new array after removing the specified elements.
1let array = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry']; 2let [firstElement, ...newArray] = array; // Removes 'Apple' 3console.log(newArray); // Output: ['Banana', 'Cherry', 'Date', 'Elderberry'] 4
In this example, the first element is removed from the original array, and the remaining elements are assigned to the new array.
The rest operator creates a new array by collecting all remaining elements after the removed elements. It doesn't mutate the original array, making it a great choice when you want to keep the original array intact.
1let array = [1, 2, 3, 4, 5]; 2let [firstElement, ...newArray] = array; 3console.log(array); // Output: [1, 2, 3, 4, 5] 4console.log(newArray); // Output: [2, 3, 4, 5] 5
JavaScript doesn't natively support negative indices for arrays. However, you can create a function to handle negative indices, which can be useful for removing elements from the end of an array.
1function removeByNegativeIndex(array, index) { 2 return index >= 0 ? array.splice(index, 1) : array.splice(array.length + index, 1); 3} 4 5let array = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry']; 6removeByNegativeIndex(array, -1); // Removes 'Elderberry' 7console.log(array); // Output: ['Apple', 'Banana', 'Cherry', 'Date'] 8
A while loop can remove multiple items from a JavaScript array based on a condition. This can be useful when you don't know the exact number of elements to remove.
1let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 2while (array.length > 5) { 3 array.pop(); // Removes the last element until the array length is 5 4} 5console.log(array); // Output: [1, 2, 3, 4, 5] 6
In this example, the while loop removes the last element from the array until the array length is 5.
In this blog, we have explored various ways to remove elements from a JavaScript array, from basic methods like splice, delete, pop, and shift to more advanced techniques using the rest operator, negative indices, and while loops.
Each method to remove elements has its unique characteristics and use cases. The splice method can remove, replace, or insert elements but mutate the original array. The delete operator removes an element but leaves an 'undefined' hole in the array. The filter method returns a new array containing elements that pass a test while leaving the original array unmodified. The pop and shift methods remove elements from the ends of an array, also mutating the original array.
The rest operator can create a new array for more advanced techniques by omitting specific elements, without mutating the original array. A custom function can handle negative indices to remove elements from the end of an array. A while loop can remove multiple items based on a condition.
Keep harnessing the power of JavaScript arrays to elevate your coding proficiency.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.