Reputation: 371
I have an array of objects that looks like this
[
{ id: 1, state: 'PURCHASED' },
{ id: 2, state: 'PURCHASED' },
{ id: 3, state: 'SOLD' },
{ id: 1, state: 'SOLD' },
{ id: 4, state: 'PURCHASED' },
{ id: 6, state: 'SOLD' },
{ id: 9, state: 'PURCHASED' }
]
I would like to filter this array such that I get the items which were PURCHASED but never SOLD. The out would look something like this
[
{ id: 2, state: 'PURCHASED' },
{ id: 3, state: 'SOLD' },
{ id: 4, state: 'PURCHASED' },
{ id: 6, state: 'SOLD' },
{ id: 9, state: 'PURCHASED' }
]
Upvotes: 1
Views: 51
Reputation: 386540
You could find the index by looking for same id
and if exist, delete this item.
var data = [{ id: 1, state: 'PURCHASED' }, { id: 2, state: 'PURCHASED' }, { id: 3, state: 'SOLD' }, { id: 1, state: 'SOLD' }, { id: 4, state: 'PURCHASED' }, { id: 6, state: 'SOLD' }, { id: 9, state: 'PURCHASED' }],
result = data.reduce((r, o) => {
var index = r.findIndex(q => o.id === q.id);
if (index === -1) r.push(o);
else r.splice(index, 1);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1