In this article, we will learn how to remove a specific item from an array in JavaScript. I have specially written this article for less experienced developers and anyone looking to achieve the same task.
I encountered a situation where I had to remove multiple items from an array object. There are several ways to remove a specific item from an array. Now, we will explore some of the easiest techniques to accomplish this task.
As you can see in the code above, I have created an array and I'm using the `.push()` method to add elements to the array. Now, I want to delete or remove a specific element from this array. For that purpose, I have created a global generic function called `.DeleteItem()`, so that you can use it similar to the `.push()` method.
Something like this:
.DeleteItem(“John”)
This function removes all of the items from the array that match with arguments.
Using using indexOf and splice
<!DOCTYPE html>
<html>
<head>
<title>Deleting array elements in JavaScript</title>
</head>
<body>
<script type="text/javascript">
const employeearray = ["John", "Smith", "Ally", "Mark", "Smith"];
function DeleteItem(array) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && array.length) {
what = a[--L];
while ((ax = array.indexOf(what)) !== -1) {
array.splice(ax, 1);
}
}
return array;
}
DeleteItem(employeearray,"Smith");
console.log(employeearray);
</script>
</body>
</html>
Above JavaScript code defines an array called `employeearray` containing five strings: "John", "Smith", "Ally", "Mark", and "Smith". The code also defines a function named `DeleteItem` which takes an array (`array`) and one or more items to delete from that array.
The function loops through the provided arguments starting from the last one (`L` is the number of arguments passed). It then iterates over the `array` searching for occurrences of each item specified in the arguments. If it finds a matching item (`what`), it removes it from the array using the `splice` method.
After defining the array and the function, the code calls `DeleteItem` with two arguments: the `employeearray` and the string "Smith". This means it wants to remove all occurrences of "Smith" from the `employeearray`.
Finally, the code prints the modified `employeearray` to the console using `console.log()`. This would output the array without the removed "Smith" elements.
Using Filter
<script type="text/javascript">
//With A one-liner code using filter,
// Remove item 'seven' from array
var filteredAry1 = employeearray.filter(function (e) { return e !== 'Smith' })
//or
var filteredAry2 = employeearray.filter(e => e !== 'Smith')
console.log(filteredAry1)
console.log(filteredAry2)
</script>
Above JavaScript code removes all occurrences of the string "Smith" from the employeearray using the filter method. Here's how it works:
filter is a method available for arrays in JavaScript. It creates a new array with all elements that pass the test implemented by the provided function.
In this code, employeearray.filter(function (e) { return e !== 'Smith' }) and employeearray.filter(e => e !== 'Smith') are two equivalent ways to use filter. They both create a new array (filteredAry1 and filteredAry2 respectively) that contains all elements of employeearray except those equal to "Smith".
The arrow function e => e !== 'Smith' (used in the second example) is a concise way of writing a function that takes an argument e and returns true if e is not equal to "Smith", and false otherwise.
The filtered arrays (filteredAry1 and filteredAry2) are then printed to the console using console.log().
This code removes all occurrences of "Smith" from the employeearray using the filter method and prints the filtered arrays to the console.
Using Move on Trick
<script type="text/javascript"> //Find and move (move): function removebymove(arr, val) { var j = 0; for (var i = 0, l = arr.length; i < l; i++) { if (arr[i] !== val) { arr[j++] = arr[i]; } } arr.length = j; } removebymove(employeearray, 'Smith') console.log(employeearray); </script>
It works better if you only want to remove or delete one occurrence of an element. There are many excellent ways to achieve this task; you can choose one of them for your solution.
This JavaScript function, named removebymove, is designed to remove all occurrences of a specified value (val) from an array (arr). Here's a breakdown of how it works:
The function accepts two parameters: arr, which is the array from which elements need to be removed, and val, which is the value to be removed from the array.
It initializes a variable j to 0. This variable will be used as an index for the new array where elements that are not equal to val will be stored.
It then iterates over each element of the input array arr using a for loop. The loop starts at index 0 and continues until it reaches the length of the array (l).
Inside the loop, it checks if the current element (arr[i]) is not equal to the specified value (val). If this condition is true, it means the element should be kept in the array. In this case, it assigns the current element to the index j of the array (arr[j++] = arr[i]). After assigning the element, it increments j by 1 to prepare for the next element.
If the current element is equal to val, it means the element should be removed, so it simply skips the assignment step.
After iterating through all elements of the array, the function sets the length property of the array (arr.length) to j. This step effectively truncates the array to contain only the elements that were not equal to val, as all elements beyond index j are removed.
The function does not explicitly return anything, but it directly modifies the input array arr.
When you call this function with removebymove(employeearray, 'Smith'), it removes all occurrences of the string "Smith" from the employeearray.
Read Similar Articles
- [Solved]-"java.lang.illegalstateexception: error processing condition on org.springframework.boot.autoconfigure.context.propertyplaceholderautoconfiguration.propertysourcesplaceholderconfigurer"
- Error: cannot import name 'PDFDocument' from 'pdfminer.pdfparser'
- Client-side Data Compression and Decompression with JavaScript
- Crud operations using stored procedure and entity framework in asp.net core