Home > Article > Web Front-end > How to Remove an Object from a JavaScript Array Based on a Specific Criterion?
Remove Object from Array using JavaScript
Problem:
How do I remove an object from an array based on a specific criterion? For instance, I want to remove the object with the name "Kristian" from someArray:
someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
Desired Output:
someArray = [{name:"John", lines:"1,19,26,96"}];
Solution:
There are several methods to remove items from an array in JavaScript:
In your case, you can use Array.splice to remove the object with the name "Kristian":
someArray.splice(someArray.findIndex(obj => obj.name === "Kristian"), 1);
Another option is to use Array.filter to create a new array without the object you want to remove:
const result = someArray.filter(obj => obj.name !== "Kristian");
If you have an object with a specific index you want to remove, use Array.splice:
someArray.splice(x, 1);
Alternatively, you can use Array.slice to achieve the same result:
someArray = someArray.slice(0, x).concat(someArray.slice(x + 1));
Remember, some methods modify the original array, while others return a new one. Choose the approach that best suits your specific needs.
The above is the detailed content of How to Remove an Object from a JavaScript Array Based on a Specific Criterion?. For more information, please follow other related articles on the PHP Chinese website!