Home > Web Front-end > JS Tutorial > How to Remove an Object from a JavaScript Array Based on a Specific Criterion?

How to Remove an Object from a JavaScript Array Based on a Specific Criterion?

Mary-Kate Olsen
Release: 2024-11-23 00:36:20
Original
328 people have browsed it

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"}];
Copy after login

Desired Output:

someArray = [{name:"John", lines:"1,19,26,96"}];
Copy after login

Solution:

There are several methods to remove items from an array in JavaScript:

  1. Array.shift(): Removes the first element.
  2. Array.slice: Returns a new array with a subset of elements.
  3. Array.splice: Modifies the original array, removing elements from a specified index.
  4. Array.pop(): Removes the last element.
  5. Array.slice(0, array.length -1): Returns a new array with all elements except the last one.
  6. Array.length = array.length - 1: Modifies the length of the array, removing the last element.

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);
Copy after login

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");
Copy after login

If you have an object with a specific index you want to remove, use Array.splice:

someArray.splice(x, 1);
Copy after login

Alternatively, you can use Array.slice to achieve the same result:

someArray = someArray.slice(0, x).concat(someArray.slice(x + 1));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template