Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

Javascript Array.prototype.filter() not working

I have this piece of code running on the client that filters a list of events:

if (res)
{
    eventList.filter(function(event) {

        const out = res.find(function(visibility) { return visibility.ID == event.id; }) == undefined;
        return out;
    });

    alert(eventList);
}

displayEvents(eventList);

The problem is that even when out is false the element is not filtered out.

Just for debug I tried to return false in any case and the resulting array still had all the initial elements:

eventList.filter(function(event) {

    return out;
});

What am I doing wrong here??

EDIT:

res is an array of JSON objects (containg only ID field) returned by the server, while eventList is a list of Facebook events, passed to this callback function from a Facebook API request

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Array.prototype.filter does not change array inplace, it returns new array made of items that satisfies the provided predicate. It should look like this

var result = eventList.filter(function(event) {
    return res.find(function(visibility) { return visibility.ID == event.id; }) === undefined;
});

You don't need to declare and assign variable and then return it from function, you can simply return expression


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...