forEach filtering by the parameter that was passed

1

I'm trying to solve a problem here. I think it's easy, but I'm not as intimate with javascript yet. Next: I have a Javascript array that has some information I need, such as name and title (eg: John, Higher Education) The first time I call the screen, all data is loaded and filled into that array. But when I click on a button with a certain titration, it needs to load all the teachers that contain that same titration and mount a grid. What I need, basically is to make a foreach and filter out all the teachers that contains that particular titration. Here is the structure of the function:

function carregarDadosJ(titulacao) {
    var dataSource = data.forEach(titulacao);

    $("#divDadosDocentes").kendoGrid({
        dataSource: dataSource,
        selectable: true,
        change: onChange,
        height: 750,
        filterable: true,
        columns: [{
            field: "Nome",
            title: "Nome",
            width: 200
        }]
    });
};
    
asked by anonymous 27.04.2015 / 16:48

1 answer

1
Assuming that titulacao is a string, and data is an array of objects, you can filter the array using the .filter() method of the array, like this:

function carregarDadosJ(titulacao) {
    // O método filter itera entre os itens da array e 
    // para cada um dos itens, a função passada será executada.
    // O filter retorna uma array com os itens os quais,
    // quando passado para a função, retorna true.
    var dataSource = data.filter(function (item, index, list) {
        // item  -> item da array
        // index -> indice do item na array
        // list  -> a própria array

        // Aqui deve ser executado o seu critério de filtro
        return item.titulacao === titulacao;
    });

    $("#divDadosDocentes").kendoGrid({
        dataSource: dataSource,
        selectable: true,
        change: onChange,
        height: 750,
        filterable: true,
        columns: [{
            field: "Nome",
            title: "Nome",
            width: 200
        }]
    });
};

Important to remember that the original array will not be mutated, the filter returns a new array with the filtered items.

Compatibility

The compatibility of the filter , foreach , and other methods, specified in version 5 of ecmascript, are not compatible with older browsers and IE < 9. If you need this compatibility, use lodash , which changes almost nothing syntax:

var dataSource = _.filter(data, function (item, index, list) { ... });
    
27.04.2015 / 21:35