首頁 >web前端 >js教程 >如何在 JavaScript 中以屬性值高效過濾數組物件?

如何在 JavaScript 中以屬性值高效過濾數組物件?

Barbara Streisand
Barbara Streisand原創
2024-10-29 14:45:021076瀏覽

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

按屬性值過濾數組對象

要根據特定屬性有效地從數組中刪除對象,請考慮以下解決方案:

1。就地過濾:

要正確減少數組長度,請在刪除項目後實現遞減 i:

<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。覆蓋元素:

覆蓋要保留的元素以避免線性時間刪除:

<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.雜湊集最佳化:

對於現代運行時,使用雜湊集來加速查找:

<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.可重用函數(可選):

將過濾操作包裝在可重複使用函數中:

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

這些解決方案根據指定的屬性值有效地過濾和刪除數組中的物件。

以上是如何在 JavaScript 中以屬性值高效過濾數組物件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn