Home > Web Front-end > JS Tutorial > body text

How to Efficiently Remove Objects from an Array Based on a Property Value?

Patricia Arquette
Release: 2024-11-01 12:41:02
Original
927 people have browsed it

How to Efficiently Remove Objects from an Array Based on a Property Value?

Remove Objects from Array by Object Property

To remove objects from an array based on a specific property, utilize native JavaScript methods and avoid issues caused by diminishing length during splice operations.

Firstly, determine the objects to be deleted and store them in a variable, such as listToDelete. Next, iterate through the array of objects (arrayOfObjects) and check if the object's ID property matches any ID in listToDelete. If a match is found, use splice to remove the object from arrayOfObjects.

To address the issue of diminishing length during splice operations, decrement the i variable each time an object is removed. Alternatively, write the elements to be kept over the array:

<code class="javascript">for (var i = 0; i < arrayOfObjects.length; i++) {
  var obj = arrayOfObjects[i];

  if (listToDelete.indexOf(obj.id) !== -1) {
    arrayOfObjects.splice(i, 1);
    i--;
  }
}
Copy after login
<code class="javascript">var end = 0;

for (var i = 0; i < arrayOfObjects.length; i++) {
  var obj = arrayOfObjects[i];

  if (listToDelete.indexOf(obj.id) === -1) {
    arrayOfObjects[end++] = obj;
  }
}

arrayOfObjects.length = end;
Copy after login

For efficient lookup in modern runtimes, utilize a hash set:

<code class="javascript">const setToDelete = new Set(listToDelete);
...
if (setToDelete.has(obj.id)) {...}
Copy after login

Finally, encapsulate the logic in a reusable function for convenient use:

<code class="javascript">const filterInPlace = (array, predicate) => {
  let end = 0;

  for (let i = 0; i < array.length; i++) {
    const obj = array[i];

    if (predicate(obj)) {
      array[end++] = obj;
    }
  }

  array.length = end;
};</code>
Copy after login

This approach effectively removes objects from an array by matching their property values and ensures optimal performance by avoiding linear-time operations.

The above is the detailed content of How to Efficiently Remove Objects from an Array Based on a Property Value?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!