Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-10-29 14:45:02
Original
1069 people have browsed it

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

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

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

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

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!

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