1

I have two arrays

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

and

b = [{

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

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

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

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

I want to remove objects from b whose feedsources are not defined in a.

So far I have tried

 b.forEach(function(e) {    

                            var indexVal = b.indexOf(e);

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

                                 console.log(e.feedsource);

                                 b.splice(indexVal,1);

                             }                                                                          
                        });

But it doesnt seems to work and I still see the elements that shouldn't be there as well as elements that should be there getting removed. What am I doing wrong in my function ?

2 Answers 2

2

A better solution would be to not alter the original array, but instead creating a new, filtered array. Luckily, JavaScript provides .filter() to help you with that!

var c = b.filter(function(el) {
    // Only keep those where the following is true
    return a.indexOf(el.feedsource) > 0;
});
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, I don't mind this if it works. let me give it a shot and see if this works.
Worth noting that if you are supporting old IE, you will need a polyfill for this. Can find one here: developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
@Paddy We're in 2015. If he needs to support old IE, he knows his workflow is bound to be abnormal. And in all case, may God have mercy upon his soul.
@MadaraUchiha - there are quite a few of us around constrained by clients :) It's still something worth noting.
I am not supporting old IE so this shouldnt be a problem and it worked well
0

Create a filtered array with lodash filter():

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

Mutate the existing array with lodash remove():

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.