Home >Web Front-end >JS Tutorial >How to Efficiently Filter Array Objects by Property Value in JavaScript?

How to Efficiently Filter Array Objects by Property Value in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-29 14:45:021100browse

How to Efficiently Filter Array Objects by Property Value in JavaScript?

Filtering Array Objects by Property Value

To efficiently remove objects from an array based on a specific property, consider the following solutions:

1. In-Place Filtering:

To decrement the array length correctly, implement decrementing i after removing an item:

<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--;
    }
}

2. Overwriting Elements:

Overwrite elements you want to keep to avoid linear-time deletions:

<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;

3. Hash Set Optimization:

For modern runtimes, use a hash set to speed up lookups:

<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;

4. Reusable Function (Optional):

Wrap the filtering operation in a reusable 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;
};

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));
console.log(arrayOfObjects); // [{id: 'hij', name: 'ge'}]</code>

These solutions efficiently filter and remove objects from the array based on their specified property values.

The above is the detailed content of How to Efficiently Filter Array Objects by Property Value in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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