Search code examples
javascriptarrayslodash

how to find a filtered array in lodash?


i am working on lodash in which i need to filtered the data from big collection of array.The collection of array is this type of data:

[ { poll_options: [ [Object] ],
    responder_ids: [ '5a7189c14615db31ecd54347', '59ffb41f62d346204e0a199b' ],
    voted_ids: [ '5a7189c14615db31ecd54347' ],
    _id: 5a7878833a1bf4238ddc5cef },
  { poll_options: [ [Object] ],
    responder_ids: [ '5a7189c14615db31ecd54347' ],
    voted_ids: [ '5a7189c14615db31ecd54347' ],
    _id: 5a787756217db51698ea8fd6 } ]

I want to filter array of which contain the value of ids which is not in voted_ids(i.e for first object it should return this 59ffb41f62d346204e0a199b nd for second collections it should return empty array) that means i have to return only those values which are not on voted_ids but in responder_ids. my code is this

_.map(polls,(poll) => {
                        // console.log(poll.responder_ids)
                        return _.filter(poll.responder_ids,(responder) => {
                          return _.find(poll.voted_ids,(voted) => {
                            return !_.includes(responder,voted)
                          })

but it does not returning filtered array istead it return whole collections.Where I am doing wrong??

Now its returning result like this...

[ [ '59ffb41f62d346204e0a199b' ], [] ]

I want single array not multiarray.


Solution

  • You are using _.filter in a wrong way.

    Filter iterates over all items in your array. If the filter function returns true the item will be returned in the filtered array and if it returns false it will not be returned.

    You however are returning an array, which results to truthy and therefore all items are returned.

    What you want is something like:

    const polls = [
      { 
        poll_options: [ '[Object]' ],
        responder_ids: [ '5a7189c14615db31ecd54347', '59ffb41f62d346204e0a199b' ],
        voted_ids: [ '5a7189c14615db31ecd54347' ],
        _id: '5a7878833a1bf4238ddc5cef'
      },
      { 
        poll_options: [ '[Object]' ],
        responder_ids: [ '5a7189c14615db31ecd54347' ],
        voted_ids: [ '5a7189c14615db31ecd54347' ],
        _id: '5a787756217db51698ea8fd6'
      }
    ];
    
    let ids = [];
    for (let i = 0; i < polls.length; i++) {
      ids = [...ids, ...polls[i].responder_ids.filter(id => {
        return !polls[i].voted_ids.includes(id);
      })];
    }
    console.log(ids);