Niall Maher Niall Maher - 3 months ago 9
Javascript Question

Filtering array by inner array value

I have an object which contains an array which looks like this:

{
"media": [
{
"title": "Raiders of the Lost Ark",
"year": "1981",
"poster": "http://ia.media-imdb.com/images/M/MV5BMjA0ODEzMTc1Nl5BMl5BanBnXkFtZTcwODM2MjAxNA@@._V1_SY1000_CR0,0,664,1000_AL_.jpg",
"genre": ["action", "adventure"],
"type": "movie"
},
{
"title": "The Other Guys",
"year": "2010",
"poster": "http://ia.media-imdb.com/images/M/MV5BMTc0NDQzNTA2Ml5BMl5BanBnXkFtZTcwNzI2OTQzMw@@._V1_.jpg",
"genre": ["action", "comedy", "crime"],
"type": "movie"
}
]
}


I'm trying to create a filter function which will return all the items with a certain genre.

Here's the filter I made but doesn't seem to return any values.

//pretend movies equals my parsed JSON file
const Movies = json.media;

const Filter = function(array, key, value){
let i, j, filteredResults = [], item;

for(i = 0, j = array.length; i<j; i++){
item = array[i];
if(typeof item[key] !== "undefined" && item[key] === value){
filteredResults.push(item);
}
}

return filteredResults;
}

console.log(Filter(Movies, "genre", "action"));


This returns no value but should return an array with the 2 movies in it?

Answer

you can use the filter method

var medias = [
    {
        "title": "Raiders of the Lost Ark",
        "year": "1981",
        "poster": "http://ia.media-imdb.com/images/M/MV5BMjA0ODEzMTc1Nl5BMl5BanBnXkFtZTcwODM2MjAxNA@@._V1_SY1000_CR0,0,664,1000_AL_.jpg",
        "genre": ["action", "adventure"],
        "type": "movie"
    },
    {
        "title": "The Other Guys",
        "year": "2010",
        "poster": "http://ia.media-imdb.com/images/M/MV5BMTc0NDQzNTA2Ml5BMl5BanBnXkFtZTcwNzI2OTQzMw@@._V1_.jpg",
        "genre": ["action", "comedy", "crime"],
        "type": "movie"
    }
]
sortedMedias = medias.filter(elem => elem.genre.indexOf("crime")!=-1);
console.log(sortedMedias); //  [ { title: 'The Other Guys',
                           //      year: '2010',
                           //      poster: 'http://ia.media-imdb.com/images/M/MV5BMTc0NDQzNTA2Ml5BMl5BanBnXkFtZTcwNzI2OTQzMw@@._V1_.jpg',
                           //      genre: [ 'action', 'comedy', 'crime' ],
                           //      type: 'movie' } ]
Comments