首页 >web前端 >js教程 >如何在 JavaScript 中按属性值高效过滤数组对象?

如何在 JavaScript 中按属性值高效过滤数组对象?

Barbara Streisand
Barbara Streisand原创
2024-10-29 14:45:021082浏览

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