How can I correctly add an argument to a local function?

Viewed 41

I'm trying to filter an array by a given ID in a function, but I don't know how to add the ID to the filter-method

function checkIdFilter(mediaObject, subCollectionId){
    //mediaObject is allMedia[index??]
    console.log("FILTERING ON " + subCollectionId);
    return mediaObject.id == subCollectionId//check if mediaObject has certain ID here;
}
function searchMediaByCollection(subCollectionId) {

    let filteredMedia = allMedia.filter(checkIdFilter);
    // let filteredMedia = allMedia.filter(checkIdFilter(this.mo??, subCollectionId));
}

As you can see, I don't know how to correctly pass the Id to the checkIdFilter method, as it (I assume) iterates invisibly over the array.

1 Answers

A filter function takes only one parameter: the current object, so you have to wrap your function in another function, and use the closure to reach subCollectionId.

function checkIdFilter(mediaObject, subCollectionId){
    //mediaObject is allMedia[index??]
    console.log("FILTERING ON " + subCollectionId);
    return mediaObject.id == subCollectionId//check if mediaObject has certain ID here;
}
function searchMediaByCollection(subCollectionId) {
    let filteredMedia = allMedia.filter(media => checkIdFilter(media, subCollectionId);
}

or

function searchMediaByCollection(subCollectionId) {
    let filteredMedia = allMedia.filter(function(media) {
        return checkIdFilter(media, subCollectionId);
    });
}

Don't hesitate to ask details if needed ;)

Related