How to filter an array by another?

0

I'm trying to use the filter with vue, but I'm having difficulty.

Code:

list() {
    var self=this
    const list = this.programas;
    if (_.isEmpty(this.filter)) {
        return list;
    }

    return list.filter(function(item) {
        return item.funcao.indexOf(self.filter) > -1
    })
}

It works perfectly when I pass a string to the filter, however I need the filter to be an array, how do I?

This is my object:

dsgpProgramas:[
                {  
                    'categoria': 'Entidades',
                    'funcao': 'Cadastro',
                 },
                 {
                    'categoria': 'Entidades',
                    'funcao': 'Operacao',
                }, 
                {
                    'categoria': 'Entidades',
                    'funcao': 'Consulta',
                    }, 
                {
                    'categoria': 'Entidades',
                    'funcao': 'Parametros',
                }, 
              ]

this is my filter

filtro = ['cadastro','consulta']

only works when my filter looks like this:

filtro= ['cadastro']

That is, it only works when I filter the array with a single-parameter filter, but in this example I need to bring the array records where the function is equal to the register or query, not just one or the other. >     

asked by anonymous 06.02.2017 / 18:56

1 answer

2

Your problem is that indexOf looks for the value completely within array , so since you are passing an array , it must be contained and same order within the program, otherwise it is filtered / removed.

This problem can be solved with one of the two examples below (there must be other ways too).

forEach

A foreach is done on the filters and is checked each within the program functions, if any is found, the loop is broken and returned true , otherwise the loop runs to the end and returns false .

list.filter((item) => {
    self.filter.forEach((filtro) => {
        if(item.indexOf(filtro)){
            return true
        }
    }, this)

    return false
});

Lodash or _Underscore.js

For your _.isEmpty you must be using one of the two, so it's possible to do so (both are equal in this case):
The ._intersection takes all equal values between arrays and creates a new array with these values, so if they have values equal to array will not be empty and the filter will return true (due to denial of ._isEmpty );

list.filter((item) => {
    return !_.isEmpty(_.intersection(item, self.filter));
})
    
08.02.2017 / 15:54