Home > Web Front-end > JS Tutorial > How to Efficiently Remove Objects from an Array Based on Object Property in JavaScript?

How to Efficiently Remove Objects from an Array Based on Object Property in JavaScript?

Linda Hamilton
Release: 2024-11-02 20:36:30
Original
329 people have browsed it

How to Efficiently Remove Objects from an Array Based on Object Property in JavaScript?

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

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

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

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

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!

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