0

I have an array of object that is need to create a filter on. The list contains an owner_id property in the JSON...

At the moment im just looping all in the array, however the list should NOT take the ones where owner_id is equal to one of the values in my filterarray:

var filter = "[14657612, 2215375794]";

            $.ajax({
                url: 'myEndPOint',
                dataType: 'json',
                success: function(data) {
                    var media = data.media;
                    var arr = [];

                    _.filter(media, function(val){
                         //The magic should happen here, only return items that has'nt got an val.owner_id that is in "filter" array
                    });

                    for(i=0; i < media.length; i++) {
                        var thumb = media[i].thumbnail;
                        var html = "<li><img src=" + thumb + " /></li>";
                        arr.push(html);
                    }
                    $(".social-ribbon-target").append(arr);
                    $(".loading").css("display", "none");*/

                },
                error: function(error) {
                    console.log("error");
                }
            });
2

2 Answers 2

0

You defined filter has a string, instead of an array.

Change:

var filter = "[14657612, 2215375794]";

To:

var filter = [14657612, 2215375794];
Sign up to request clarification or add additional context in comments.

Comments

0

The magic should happen here

It is actually not magic, but a function that returns true or false whether the item should be in the returned array.

Assuming that your filter is an array and not a string as it is right now (otherwise you have to parse it with filter_arr = JSON.parse(filter)) you may want to write your filtering function like this:

var filter = ["one",  "two", "three"];

var media = [{owner_id: "one"}];

console.log(_.filter(media, function(item){
    return filter.indexOf(item.owner_id) >= 0;
}))
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

4 Comments

Hmm, but it doesn't match anything? _.filter(media, function(item){ console.log(filter.indexOf(item.owner_id)) return filter.indexOf(item.owner_id) >= 1; }); Even though, some it the items has item.owner_id to be something from the array of filter?
Why did you change it to >= 1 ? Have you parsed you string to array accordingly?
Woop, typing error... However, still, everything returns as false or -1 ?
indexOf returns -1 if the element is not present in the array, or index of an element

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.