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--; } }
<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;
For efficient lookup in modern runtimes, utilize a hash set:
<code class="javascript">const setToDelete = new Set(listToDelete); ... if (setToDelete.has(obj.id)) {...}
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>
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!