繁体   English   中英

如何使用另一个数组中存储的值从数组中删除元素

[英]How to remove elements from an array using values stored in another array

我有两个数组

var a = ['tayyar', '14march' ]; 

b = [{

    "feedsource": "tayyar",  
    "hash": "46cc3d067df1ea7877140c67b60e9a7a"
}, {

    "feedsource": "elmarada",
    "hash": "a9fb75f2aa4771945ec597ecf9ae49ea"
}, {

    "feedsource": "14march",
    "hash": "fce7a6a87b53358c4be47507b0dc327b"
}, {

    "feedsource": "tayyar",    
    "hash": "b85d2a9c22ac4831477de15ba24b4ac5"
}]

我想从b中删除其feedsource未定义的对象。

到目前为止,我已经尝试过

 b.forEach(function(e) {    

                            var indexVal = b.indexOf(e);

                            if(a.indexOf(e.feedsource) ==-1){

                                 console.log(e.feedsource);

                                 b.splice(indexVal,1);

                             }                                                                          
                        });

但这似乎不起作用,并且我仍然看到不应该存在的元素以及应该在那里存在的元素被删除。 我的功能出了什么问题?

更好的解决方案是不更改原始数组,而是创建一个新的过滤后的数组。 幸运的是,JavaScript提供了.filter()来帮助您!

var c = b.filter(function(el) {
    // Only keep those where the following is true
    return a.indexOf(el.feedsource) > 0;
});

使用lodash filter()创建一个过滤数组:

_.filter(b, function(item) {
    return _.includes(a, item.feedsource);
});

使用lodash remove()更改现有数组:

_.remove(b, function(item) {
    return _.includes(a, item.feedsource) === false;
});

暂无
暂无

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

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