简体   繁体   中英

How would you Filter an array of objects based on a condition

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' }
]

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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM