Reputation:
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.
Upvotes: 0
Views: 48
Reputation: 196
This is not right way to use filter
function. In the callback function you should return some boolean
value so the array could be filtered by that criteria.
If I understand you correctly you want to filter through array to get array which will contain all results when the id is in the responder_ids
but no in the voted_ids
. It could be resolved in various ways, i.e.:
_.filter(polls, poll => _.findIndex(poll.responder_ids, id => id === '59ffb41f62d346204e0a199b') > -1 && _.findIndex(poll.voted_ids, id => id === '59ffb41f62d346204e0a199b') === -1;
);
Upvotes: 0
Reputation: 3682
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);
Upvotes: 1