jQuery remove a specified item from array
In jQuery, we can remove an item from an array with the $.grep()
function.
Table of contents:
- 1. Remove one number from the array with $.grep()
- 2. Remove two numbers from array with $.grep() and $.inArray()
- 3. References
P.S Tested with jQuery 3.7.1
1. Remove one number from the array with $.grep()
The $.grep() is part of the jQuery library; this function can easily filter items from an array.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery remove item from array</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var numbers = [1, 2, 5, 4, 3, 5, 3];
var removedItem = 3; // we don't want 3
var result = $.grep(numbers, function(value) {
return value != removedItem;
});
console.log(result); // [1,2,5,4,5]
});
</script>
</head>
<body>
</body>
</html>
output
[1, 2, 5, 4, 5]
The result
will contain all the numbers from the original array except for 3.
2. Remove two numbers from array with $.grep() and $.inArray()
We can combine $.grep()
and $.inArray() to remove two or more numbers from an array.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery remove item from array</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var numbers = [1, 2, 5, 4, 3, 5, 3];
var removedNumbers = [3, 5];
var result2 = $.grep(numbers, function(value) {
// If value is not found, $.inArray() returns -1, this means
// Only include numbers not in the removedNumbers array
return $.inArray(value, removedNumbers) === -1;
});
console.log(result2); // [1,2,4]
});
</script>
</head>
<body>
</body>
</html>
output
[1, 2, 4,]
The result
will contain all the numbers from the original array except for 3 and 5.
3. References
About Author
Comments
Subscribe
0 Comments