JavaScript && Python - Removing a specific element from an array

JavaScript && Python - Removing a specific element from an array

array, Javascript

Removing one or many elements from an array in JavaScript is pretty straightforward. Though with all things programming there is some nuances that you should be aware of and there's a million ways to do it. Let's take a quick look at a few different examples to manipulate elements in JavaScript arrays.

How do I remove a specific value from an array in JavaScript?

If we have a collection of items and we simply want to trim elements off the end of the array, JavaScript offers two simple options out of the box. Below are two examples using Array.length & Array.prototype.pop().

Trimming an array using Array.length

var colors = ['red', 'orange', 'yellow', 'green'];
console.log(colors.length);
// Result: 4
colors.length = 3; // Trim last element off console.log(colors.length); // Result: 3
console.log(colors); // Result: ["red", "orange", "yellow"]

Trimming an array using Array.prototype.pop()

var plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop());
// Result: "tomato"
console.log(plants); // Result: ["broccoli", "cauliflower", "cabbage", "kale"]

Removing elements from the beginning of a JavaScript array

Now let's take a look at the inverse scenario, assume we have a collection of items and we want to remove elements from the beginning of the array. Similar to pop(), JavaScript uses Array.prototype.shift() to "shift" the first element over.

Using Array.prototype.shift() to remove the first element

var numbers = [1, 2, 3];
var firstNumber = numbers.shift();
console.log(firstNumber);
// Result: 1
console.log(numbers); // Result: [2, 3]

Using splice() to remove array elements in JavaScript

As you could have guessed, JavaScript also has a method that allows you to either remove from the beginning of an array OR trim from the end on an array. This magical method is known as Array.prototype.splice(), which takes the start and end index as parameters.

Manipulating an array with Array.prototype.splice()

var months = ['Jan', 'March', 'April', 'June'];
// Insert 'Feb' at 1st index position
months.splice(1, 0, 'Feb');
console.log(months);
// Result: ['Jan', 'Feb', 'March', 'April', 'June']

// Replace 'June' with 'May' at the 4th index position
months.splice(4, 1, 'May');
console.log(months);
// Result: ['Jan', 'Feb', 'March', 'April', 'May']

// Remove 'May' from the 4th index position
months.splice(4, 1);
console.log(months);
// Result: ['Jan', 'Feb', 'March', 'April']

// Remove 'Feb' & 'March' from the 1st & 2nd index positions
months.splice(1, 2);
console.log(months);
// Result: ['Jan', 'April']

Remove elements by value using filter()

JavaScript has a built in method to make removing array elements by their value quite easy. The Array.prototype.filter() method allows you to specify a condition in which the items that satisfy it will be removed. Check the example out below:

Filtering items by value using Array.prototype.filter()

var animals = ['dog', 'cat', 'bird', 'spaghetti'];

// Remove the value 'spaghetti' from our animal array
var filtered = array.filter(function(value, index, arr){
    return value != 'spaghetti';
});
console.log(animals);
// Result: ['dog', 'cat', 'bird']

Using the delete operator to remove JavaScript array elements

The delete operator in JavaScript behaves a bit differently than you might think. Delete removes the property from an object, what this means in English is that instead of physically removing the item, its value is set to undefined.

Removing elements using the delete operator

var fish = ['goldfish', 'carp', 'guppy', 'cod'];
// Remove the value at index 2 
delete fish[2]; // delete the guppy!
console.log(fish); // Result: ['goldfish', 'carp', undefined, 'cod']

Remove all elements in a JavaScript array

Last but not least, let's have a look at a few ways to completely nuke the array. It should be fairly straight forward to use any of the above methods to empty all elements but let's examine two common scenarios:

Empty an array using Array.length

Array.length deletes everything in the array, including other references. In other words, if you have two references to the same array and you delete the array’s contents using Array.length, both references will now point to the same empty array. Here is an example using two arrays:

var fish = ['goldfish', 'carp', 'guppy', 'cod'];
// Create a reference from the fish array var fish2 = fish;
// Remove the fish fish.length = 0;
console.log(fish); // Result: []

console.log(fish2); // Result: []

Empty an array by re-initializing the array

Emptying an array by initializing a new array assigns a reference to the new array variable, while excluding other references. This means that references to the contents of the previous array are still kept in memory, which can commonly leading to memory leaks.You can view the issue below by seeing fish2 still holds the values while fish was emptied.

var fish = ['goldfish', 'carp', 'guppy', 'cod'];
// Create a reference from the fish array var fish2 = fish;
// Remove the fish by initializing a new array fish = [];
console.log(fish); // Result: []

console.log(fish2); // Result: ['goldfish', 'carp', 'guppy', 'cod']

How do I remove a specific value from an array in Python?

To remove a specific value from an array in most programming languages, you can follow these steps:

  1. Find the index of the element that you want to remove. You can use the indexOf method in JavaScript, the index method in Python, or a loop to search for the element.

  2. Remove the element from the array using the index. You can use the splice method in JavaScript or the del or pop method in Python to remove the element.

Here's an example in Python:

arr = [1, 2, 3, 4, 5] value_to_remove = 3 if value_to_remove in arr: arr.remove(value_to_remove) print(arr) # Output: [1, 2, 4, 5]

Note that in Python, you can use the remove method to remove the first occurrence of the element. If there are multiple occurrences of the element, you'll need to use a loop or a list comprehension to remove all of them.



Back to The Programmer Blog