Home > Article > Web Front-end > How Can I Remove Objects from a JavaScript Array?
In JavaScript, there are various methods to remove objects from an array. Let's explore different approaches:
1. Array.shift() and Array.pop():
2. Array.splice():
3. Array.slice():
4. Array.filter() and Array.findIndex():
Examples:
To remove the object with the name "Kristian" from the provided array:
Destructive splice with findIndex:
let someArray = [{name: "Kristian", lines: "2,5,10"}, {name: "John", lines: "1,19,26,96"}]; someArray.splice(someArray.findIndex(v => v.name === "Kristian"), 1); console.log(someArray); // [{name: "John", lines: "1,19,26,96"}]
Nondestructive filter:
let someArray = [{name: "Kristian", lines: "2,5,10"}, {name: "John", lines: "1,19,26,96"}]; let noKristian = someArray.filter(v => v.name !== "Kristian"); console.log(someArray); // [{name: "Kristian", lines: "2,5,10"}, {name: "John", lines: "1,19,26,96"}] console.log(noKristian); // [{name: "John", lines: "1,19,26,96"}]
Choose the method that best suits your specific requirements and use it accordingly.
The above is the detailed content of How Can I Remove Objects from a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!