简体   繁体   English

高效的方法来过滤对象数组

[英]Performant way to filtering an array of objects

is this a good way to filter out all of the existing objects in an array? 这是过滤掉数组中所有现有对象的好方法吗?

var arrayOfObjects = [
        { id: 1, text: 'obj1'}, 
        { id: 2, text: 'obj2'}, 
        { id: 3, text: 'obj3'}
    ], 
    ids = [ 1, 3 ],
    filteredArray = [];

for (var x = 0, len = arrayOfObjects.length; x < len; x++) {
    for (var i = 0, ilen = ids.length; i < len; i++) {
        if (arrayOfObjects[x].id === ids[i]) {
            arrayOfObjects[x] = null;
            break;
        }
    }
}

filteredArray = _.filter(obj, function(o) { return !!(o); });

Update: The goal of this is to filter objects out of the arrayOfObjects that match an id in the ids array. 更新:此操作的目的是从与ids数组中的id匹配的arrayOfObjects中筛选出对象。 So the code above works (filteredArray is [{ id: 2, text: 'obj2'}], but is there a better way to accomplish this? 因此,上面的代码可以工作(filteredArray为[{id:2,text:'obj2'}],但是有更好的方法吗?

Yes, there is a better way of doing it: 是的,有一种更好的方法:

 var array = [ { id: 1, text: "obj1" }, { id: 2, text: "obj2" }, { id: 3, text: "obj3" } ]; var ids = [1, 3]; var idsIndex = toIndex(ids); var result = array.filter(function (obj) { return !idsIndex.hasOwnProperty(obj.id); }); alert(JSON.stringify(result, null, 4)); function toIndex(array) { var length = array.length; var result = {}; var index = 0; while (index < length) result[array[index++]] = true; return result; } 

The documentation of the toIndex function is in the following answer (note that it's called index_of_array instead): https://stackoverflow.com/a/28358301/783743 toIndex函数的文档在以下答案中(请注意,它index_of_arrayindex_of_array ): https : index_of_array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM