Operation of Array.filter() in Javascript

Asked

Viewed 219 times

1

Hello! I am trying to generate an array with only a "result". Basically I do a query in Amazon that returns all calls made.

I want to generate an array containing only the completed calls, which in the database are stored as status = 'F'. I will use this array to generate a graph.

In my view I opened a script tag and put the following:

 var teste = [];

    teste.filter(function (){
        if(status == 'F'){

        }
    });

And this is where my doubt comes from, in this Function() I have to pass an object? (In this case this object would be the collection of Mongo or something I imagine). And then if the status is F, I add in the array, if not, no.

That’s kind of how the filter works or I’m wrong?

1 answer

3


the filter gets a callback, that is, a function that receives as one of the arguments the elements contained in array.

I understand you have a array[{}] of objects, as represented in the variable dados.

In practice:

let dados = [{
        'id': 1,
        'status': 'F'
    },
    {
        'id': 2,
        'status': 'M'
    },
    {
        'id': 3,
        'status': 'F'
    }
]


let novoArray = dados.filter(finalizados);

console.log(novoArray);

function finalizados(value) {
    return value.status === 'F';
}

  • Yeah, I imagine it’s right there. That finished would be the array generated after the filter?

  • @finished danibrum is the method that filters through status='F'

  • 1

    Ah I get it, I’ll see if I can make it work with the database here, thank you very much!

  • 1

    @Danibrum takes a look at the documentation, has no secret :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.