Home >Web Front-end >JS Tutorial >How to Efficiently Remove Objects from an Array Based on Properties in JavaScript?
Using Native JavaScript to Remove Objects from Array by Object Property
When working with arrays of objects, removing specific objects based on properties can be essential. However, simply using splice() can lead to complications due to the diminishing array length. Here's how to overcome this issue using native JavaScript techniques:
Decrementing i After Deletion:
To fix the issue with splice, decrement i after each deletion to account for the shifted index. This prevents the skipping of array elements and ensures that all target objects are removed.
for (var i = 0; i < arrayOfObjects.length; i++) { var obj = arrayOfObjects[i]; if (listToDelete.indexOf(obj.id) !== -1) { arrayOfObjects.splice(i, 1); i--; } }
Rewriting Array Elements:
To avoid linear-time deletions, you can rewrite only the elements you want to keep over the array.
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;
Using a Hash Set:
For faster lookups, use a hash set to store the IDs of objects to be deleted.
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;
Reusable Function:
Wrap this logic into a reusable function for convenience.
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; }; const toDelete = new Set(['abc', 'efg']); const arrayOfObjects = [{id: 'abc', name: 'oh'}, {id: 'efg', name: 'em'}, {id: 'hij', name: 'ge'}]; filterInPlace(arrayOfObjects, obj => !toDelete.has(obj.id));
The above is the detailed content of How to Efficiently Remove Objects from an Array Based on Properties in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!