Removing Objects from an Array Based on Object Property
In JavaScript, deleting an object from an array by matching a specific property can be challenging. This is because using the splice method, as commonly attempted, leads to a diminished array length as deletions occur.
Fix for Using Splice Method
To resolve this issue, you can implement a fix by decrementing the loop index when a deletion occurs:
<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--; } }
Overwriting Array Elements
Alternatively, you can avoid linear-time deletions by progressively overwriting the array elements you want to keep:
<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;
Hash Set for Lookups
For efficient lookups, you can utilize a hash set:
<code class="javascript">const setToDelete = new Set(listToDelete); let end = 0; for (let i = 0; i < arrayOfObjects.length; i++) { const obj = arrayOfObjects[i]; if (setToDelete.has(obj.id)) { arrayOfObjects[end++] = obj; } } arrayOfObjects.length = end;
Helper Function
Encapsulate this approach into a helper function:
<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>
The above is the detailed content of How to Efficiently Remove Objects from an Array Based on Object Property in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!