In this post explained how to remove item from array example. We will learn jquery remove item from array. We will see multiple example of jquery remove value from array by value.
I will give you different method to delete array element by value in jquery. first we will use splice() and inArray() for remove key value by value.
We have explained the method below.
- splice(): – to remove an item by its index.
- inArray(): to find specific index from array.
- $.grep(): JQuery provides a built-in utility method called $.grep() that filters an array based on a condition and returns a new array containing the items that match the condition.
You can see both example with output so, you can understand, how it works.
1. JQuery remove item from array using splice() and inArray() method.
Example:
var data = ["Red", "Green", "Blue", "black"];
data.splice($.inArray('Green', data), 1);
console.log(data);
Output:
["Red", "Blue", "black"];
2. JQuery remove item from array using $.grep() method
It’s commonly used when you want to filter out certain values or items from an array based on a condition.
Syntax:
$.grep(array, function(element, index), [invert]);
- array: The array to be filtered.
- function(element, index): A function to test each element of the array. It should return true to keep the element, or false to remove it.
- invert: Optional, if set to true, it invents the selection by returning items that do not match the condition.
Example:Basic using $.grep() method
let arrValue = [10, 11, 12, 13, 14];
// Filter array to keep only even numbers
let filterArray = $.grep(arrValue, function(value) {
return value % 2 == 0;
});
console.log(filterArray); // Output: [10, 12, 14];
Example: Using the invert Parameter
Jquery remove item from array using $.grep() method with invert Parameter. If you want to return elements that do not match the condition, you can use the invert parameter.
let arrValue = [10, 11, 12, 13, 14];
// Remove even numbers by setting invert to true
let filterArray = $.grep(arrValue, function(value) {
return value % 2 == 0;
}, true);
console.log(filterArray); // Output: [11, 13, 15];
I hope this tutorial help you.