最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Array.prototype.filter() not working - Stack Overflow

programmeradmin6浏览0评论

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

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

Share Improve this question edited Oct 7, 2017 at 14:36 Andrzej Smyk 1,72411 silver badges21 bronze badges asked Oct 7, 2017 at 10:14 SneppySneppy 3867 silver badges20 bronze badges 2
  • 2 .filter() doesn't change the original array. You need to do eventList = eventList.filter(..). Also, don't use alert() for debugging. – JJJ Commented Oct 7, 2017 at 10:17
  • God, how can I be that stupid ... Thanks! – Sneppy Commented Oct 7, 2017 at 10:18
Add a ment  | 

1 Answer 1

Reset to default 7

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

发布评论

评论列表(0)

  1. 暂无评论