2

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?

7
  • 2
    Movies.filter(m => m.genre.includes('action')) Commented Aug 7, 2016 at 9:31
  • 1
    In your implementation: item[key] === value here you're comparing an array with a string. Commented Aug 7, 2016 at 9:33
  • Please study what JSON is and is not. This is not JSON. It is just a JavaScript object. Also, this is not about "sorting" it seems to be about "filtering". Finally, how is this related to ES6? Commented Aug 7, 2016 at 9:42
  • Wow that's a really nice implementation thanks @zekms Commented Aug 7, 2016 at 9:43
  • 1
    To solve your problem, you could "debug" it, by stepping through it line by line with the debugger. Focus on the line containing the if. Break on that line, and examine the variables item[key] and value and you should be able to see why the condition is not being met. Commented Aug 7, 2016 at 9:50

7 Answers 7

4

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' } ]
Sign up to request clarification or add additional context in comments.

Comments

3

You were almost there. There is just one point to be changed :

  • The 'genre' property is itself an array so the 'indexOf' the 'action'
    parameter must be checked

    const Filter = function(obj, key, value) {
        let i, j, filteredResults = [], item;
    
        // The media property is the array in which we want to search 
        let array = obj.media;
    
        for(i =  0, j = array.length; i < j; i++){
            item = array[i];
    
            // the genre property is itself an array
            // so we'll need to find the 'indexOf' the item
            // rather than comparing directly
    
            if(typeof item[key] !== "undefined" && item[key].indexOf(value) !== -1){
                filteredResults.push(item);
            }
        }
    
        return filteredResults;
    }
    

Comments

0

Use this

if(_.contains(item[key], value)){
  filteredResults.push(item);
}

instead of

if(typeof item[key] !== "undefined" && item[key] === value){
  filteredResults.push(item);
}

1 Comment

Not tagged Underscore, please provide native solution.
0

I think you should keep it simple. I maybe something like this would suit you

function movieFilter (where, field, search) {
  if (typeof search !== "string") { search = search.toString()}; //for example if you want to search by the year, and you provide integer search number
  return where.filter(item => {
    return item[field].toLowerCase().indexOf(search.toLowerCase()) !== -1;
  })
}

Here is a playground example of this function https://jsbin.com/tepifa/edit?js,console

Comments

0

If you are trying to make a generic filter function, you should consider few cases:

  • Strict Equality (===)
  • Loose Equality (==)
  • partOf

var d = {
  "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"
  }]
}
var _g = "action";
function filter(array, key, value, operation) {
  return array.filter(x=>{
    switch(operation){
      case "contains": return x[key].indexOf(value)>-1;
      case "ignoreType": return x[key] == value;
      default: return x[key] === value;
    }
  })
}
console.log(filter(d.media, "genre", "action", "contains"))
console.log(filter(d.media, "year", 2010))
console.log(filter(d.media, "year", 2010, "ignoreType"))

Comments

0
    item[key].forEach(function(oneDoc){

        if(oneDoc == value){
            filteredResults.push(item);
        }
    })

Comments

0

First Need to find index of value. If the index is not -1 that means value is persent in array.

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

Comments

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.